Linear Search in Java
Problem
Linear search checks every element of an array one at a time, from start to end, until it finds the target value or runs out of elements to check.
Given an array of integers and a target value, find the index of the target, or report that it isn't present.
Java Program
public class LinearSearch {
public static void main(String[] args) {
int[] arr = {12, 5, 19, 7, 3};
int target = 19;
int index = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) {
index = i;
break; // found the target, no need to keep scanning
}
}
System.out.println("Element found at index: " + index);
}
}Output
Core Logic
Checking every element against the target, one at a time from the start, is the most direct way to search when the array isn't sorted.
- 1
indexstarts at-1, the conventional way to signal 'not found yet'. - 2A loop visits each element of
arrby index, from0toarr.length - 1. - 3
if (arr[i] == target)checks whether the current element matches the target. - 4The first match sets
indexto that position and exits the loop immediately withbreak.
[12, 5, 19, 7, 3] searching for 19, the scan checks 12, then 5, then finds 19 at index 2 and stops.Key Point: Linear search works on any array, sorted or not — the trade-off is that it may have to check every single element in the worst case, unlike binary search's faster approach on sorted data.
Why: In the worst case every element is checked once before finding a match or reaching the end, with only the index variable kept in memory.
Key Concepts
Approach 2: Java 8
import java.util.stream.IntStream;
public class LinearSearchStream {
public static void main(String[] args) {
int[] arr = {12, 5, 19, 7, 3};
int target = 19;
// filter() keeps matching indices; findFirst() takes the first one, or -1 if none
int index = IntStream.range(0, arr.length)
.filter(i -> arr[i] == target)
.findFirst()
.orElse(-1);
System.out.println("Element found at index: " + index);
}
}
Output
Core Logic
The same element-by-element check can filter a stream of indices down to the ones matching the target, then take the first.
- 1
IntStream.range(0, arr.length)generates every valid index into the array. - 2
.filter(i -> arr[i] == target)keeps only the indices whose element matches the target. - 3
.findFirst()takes the first surviving index, wrapped in anOptionalInt, or empty if none matched. - 4
.orElse(-1)falls back to-1if the target wasn't found anywhere.
[12, 5, 19, 7, 3] and target 19, filtering keeps only index 2, and findFirst() returns it directly.Key Point: findFirst() short-circuits the same way the loop's break did — it doesn't keep scanning once a match has been found.
Why: findFirst() stops as soon as it finds a matching index, the same short-circuiting behavior as the loop's break.