0
0
JavaProgramBeginner · 2 min read

Java Program for Linear Search with Example and Explanation

A Java program for linear search uses a for loop to check each element in an array one by one until it finds the target value or reaches the end, like this: for (int i = 0; i < arr.length; i++) { if (arr[i] == target) return i; }.
📋

Examples

Inputarr = {2, 4, 6, 8, 10}, target = 6
OutputElement found at index 2
Inputarr = {1, 3, 5, 7, 9}, target = 4
OutputElement not found
Inputarr = {}, target = 1
OutputElement not found
🧠

How to Think About It

To find a number in a list, start from the first item and check each one in order. If the item matches the number you want, stop and say where it is. If you reach the end without finding it, say it is not there.
📐

Algorithm

1
Start from the first element of the array.
2
Compare the current element with the target value.
3
If they are equal, return the current index.
4
If not, move to the next element.
5
Repeat until the end of the array.
6
If the target is not found, return -1.
💻

Code

java
public class LinearSearch {
    public static int linearSearch(int[] arr, int target) {
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == target) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] numbers = {2, 4, 6, 8, 10};
        int target = 6;
        int result = linearSearch(numbers, target);
        if (result == -1) {
            System.out.println("Element not found");
        } else {
            System.out.println("Element found at index " + result);
        }
    }
}
Output
Element found at index 2
🔍

Dry Run

Let's trace the array {2, 4, 6, 8, 10} searching for 6 through the code

1

Start loop at index 0

Check if arr[0] (2) == 6 → false

2

Move to index 1

Check if arr[1] (4) == 6 → false

3

Move to index 2

Check if arr[2] (6) == 6 → true, return 2

IndexValueComparison with target
022 == 6 → false
144 == 6 → false
266 == 6 → true
💡

Why This Works

Step 1: Loop through array

The for loop goes through each element one by one to check for the target.

Step 2: Compare elements

Each element is compared with the target using == to find a match.

Step 3: Return index or -1

If a match is found, the index is returned; otherwise, -1 means not found.

🔄

Alternative Approaches

Using while loop
java
public class LinearSearch {
    public static int linearSearch(int[] arr, int target) {
        int i = 0;
        while (i < arr.length) {
            if (arr[i] == target) {
                return i;
            }
            i++;
        }
        return -1;
    }
}
Uses a <code>while</code> loop instead of <code>for</code>, functionally the same but less concise.
Using Java Streams (Java 8+)
java
import java.util.stream.IntStream;
public class LinearSearch {
    public static int linearSearch(int[] arr, int target) {
        return IntStream.range(0, arr.length)
            .filter(i -> arr[i] == target)
            .findFirst()
            .orElse(-1);
    }
}
Uses streams for a functional style, more modern but less straightforward for beginners.

Complexity: O(n) time, O(1) space

Time Complexity

Linear search checks each element once, so time grows linearly with array size.

Space Complexity

No extra space is needed besides variables, so space is constant.

Which Approach is Fastest?

All linear search methods have the same time complexity; streams add overhead but improve readability.

ApproachTimeSpaceBest For
For loopO(n)O(1)Simple and clear code
While loopO(n)O(1)Same as for loop, less concise
Java StreamsO(n)O(1)Modern style, functional programming
💡
Always check if the array is empty before searching to avoid errors.
⚠️
Beginners often forget to return -1 when the element is not found, causing incorrect results.