Java Program to Find an Element Using Linear Search

In this Java program, we will learn how to find an element in an array using Linear Search.

What is Linear Search?

Linear Search is a simple searching technique in which each element of an array is checked one by one until the required element is found.

For example:

Array  : {10, 20, 30, 40, 50}
Search : 30
Output : Element found at index 2

The search starts from the first element and continues until the element is found.


1. Traditional Java Program Using for Loop

import java.util.Scanner;

public class LinearSearch {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] arr = {10, 20, 30, 40, 50};
        System.out.print("Enter element to search: ");
        int search = sc.nextInt();
        int index = -1;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == search) {
                index = i;
                break;
            }
        }
        if (index != -1) {
            System.out.println("Element found at index: " + index);
        } else {
            System.out.println("Element not found");
        }
        sc.close();
    }
}

Output

Enter element to search: 30
Element found at index: 2

Explanation

The program checks each element using a for loop:

for (int i = 0; i < arr.length; i++) {
    if (arr[i] == search) {
        index = i;
        break;
    }
}

If the current array element matches the search value:

arr[i] == search

the index is stored and the loop stops using break.

For example:

Index :  0   1   2   3   4
Array : 10  20  30  40  50
                  ↑
               Found

Therefore, 30 is found at index 2.


2. Java 8 Program Using Stream API

Java 8 provides the Stream API, which can be used to perform a linear search in a simple functional style.

import java.util.Scanner;
import java.util.stream.IntStream;

public class LinearSearchJava8 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] arr = {10, 20, 30, 40, 50};
        System.out.print("Enter element to search: ");
        int search = sc.nextInt();
        int index = IntStream.range(0, arr.length)
                .filter(i -> arr[i] == search)
                .findFirst()
                .orElse(-1);
        if (index != -1) {
            System.out.println("Element found at index: " + index);
        } else {
            System.out.println("Element not found");
        }
        sc.close();
    }
}

Output

Enter element to search: 40
Element found at index: 3

Explanation of Java 8 Program

IntStream.range() creates a stream of array indexes:

IntStream.range(0, arr.length)

The filter() method checks whether the element at each index matches the search value:

.filter(i -> arr[i] == search)

Here, i -> is a Java 8 lambda expression.

The findFirst() method returns the first matching index:

.findFirst()

If no element is found, orElse(-1) returns -1:

.orElse(-1)

Difference Between Traditional Java and Java 8

FeatureTraditional JavaJava 8
Approachfor loopStream API
Lambda expressionNoYes
Stream APINoYes
Easy for beginnersVery easyModerate
Returns first matchbreakfindFirst()
Java VersionAll common versionsJava 8+

Which Method Should You Use?

For beginners, the traditional for loop is recommended because it clearly shows how Linear Search works.

The Java 8 version is useful for learning Streams, Lambda expressions, filter(), and findFirst().

Time Complexity

The best-case time complexity is O(1) when the element is found at the first position.

The worst-case time complexity is O(n) when the element is at the last position or is not present in the array.

The traditional and Java 8 approaches both perform a linear search.

Conclusion

Linear Search is one of the easiest searching algorithms to understand. It checks each element one by one until the required element is found. The traditional for loop is best for learning the basic logic, while the Java 8 Stream API provides a concise functional approach.

Backend developer working with Java, Spring Boot, Microservices, NoSQL, and AWS. I love sharing knowledge, practical tips, and clean code practices to help others build scalable applications.

Leave a Reply

Your email address will not be published. Required fields are marked *