Java Program to Implement Linear Search

Java Program to Implement Linear Search

If you are new to programming, understanding how to search for elements in a dataset is a fundamental skill. Linear search is one of the simplest and most intuitive ways to find an item in a list or array. In Java, it allows beginners to practice basic concepts like loops, conditions, arrays, and functions. Even though there are faster search algorithms, linear search remains a perfect starting point for learning and building confidence in coding.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Linear search is particularly useful when working with small or unsorted datasets. It checks each element in sequence until it finds the target, making it simple to implement and understand. In this article, we will explore multiple ways to implement linear search in Java, including using loops, functions, recursion, and Java’s built-in utilities. By the end, you’ll have several working programs to practice and learn from.

Program 1: Linear Search Using a For Loop

This program demonstrates the most straightforward approach to linear search. It goes through each element of an array sequentially to find the target value.

public class LinearSearchForLoop {

    public static void main(String[] args) {

        int[] numbers = {3, 5, 7, 9, 11, 13};
        int target = 9;
        boolean found = false;

        for (int i = 0; i < numbers.length; i++) {

            if (numbers[i] == target) {

                System.out.println("Element " + target + " found at index " + i);

                found = true;
                break;

            }

        }

        if (!found) {
            System.out.println("Element " + target + " not found in the array");
        }

    }

}

In this example, the for loop iterates through each element, comparing it with the target value. If it finds a match, it prints the index and stops searching. This approach is very beginner-friendly because it clearly shows how each element is checked one by one, giving learners a concrete understanding of sequential search.

Program 2: Linear Search Using a While Loop

The while loop provides another way to implement linear search. This approach allows you to practice different looping constructs in Java.

public class LinearSearchWhileLoop {

    public static void main(String[] args) {

        int[] numbers = {10, 20, 30, 40, 50};
        int target = 30;
        int i = 0;
        boolean found = false;

        while (i < numbers.length) {

            if (numbers[i] == target) {

                System.out.println("Element " + target + " found at index " + i);

                found = true;
                break;

            }

            i++;

        }

        if (!found) {
            System.out.println("Element " + target + " not found in the array");
        }

    }

}

Here, the while loop keeps checking elements as long as the index i is less than the array length. This approach is useful because it gives beginners exposure to different control structures and shows that the same problem can be solved in multiple ways using Java.

Program 3: Linear Search Using a Function

Encapsulating linear search logic inside a function makes code reusable and organized. This program demonstrates how to write a reusable method for linear search.

public class LinearSearchFunction {

    public static int linearSearch(int[] numbers, int target) {

        for (int i = 0; i < numbers.length; i++) {

            if (numbers[i] == target) {
                return i;
            }

        }

        return -1; // returns -1 if not found

    }

    public static void main(String[] args) {

        int[] numbers = {1, 3, 5, 7, 9};
        int target = 7;
        int result = linearSearch(numbers, target);

        if (result != -1) {
            System.out.println("Element " + target + " found at index " + result);
        } else {
            System.out.println("Element " + target + " not found in the array");
        }

    }

}

This program introduces the concept of methods, making it easier to organize code and reuse the linear search logic anywhere in the program. Beginners can see the benefit of separating logic from the main method, which is a good programming practice.

Program 4: Linear Search Using Recursion

Recursion offers a different way to think about linear search. Instead of loops, the function calls itself until it finds the target or reaches the end of the array.

public class LinearSearchRecursion {

    public static int linearSearchRecursive(int[] numbers, int target, int index) {

        if (index >= numbers.length) {
            return -1; // element not found
        }

        if (numbers[index] == target) {
            return index;
        }

        return linearSearchRecursive(numbers, target, index + 1);

    }

    public static void main(String[] args) {

        int[] numbers = {2, 4, 6, 8, 10};
        int target = 6;
        int result = linearSearchRecursive(numbers, target, 0);

        if (result != -1) {
            System.out.println("Element " + target + " found at index " + result);
        } else {
            System.out.println("Element " + target + " not found in the array");
        }

    }

}

Using recursion for linear search teaches beginners how functions can call themselves to solve smaller parts of a problem. It’s a good exercise to understand recursive thinking and how programming logic can differ from iterative loops.

Program 5: Linear Search Using Java’s Built-in Arrays Utility

Java provides built-in methods that can simplify searching. Using the Arrays class, you can check if an element exists without writing loops manually.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class LinearSearchBuiltIn {

    public static void main(String[] args) {

        int[] numbers = {5, 10, 15, 20, 25};
        int target = 15;

        // Convert the array to a List<Integer>
        List<Integer> numberList = Arrays.stream(numbers)
                                         .boxed()
                                         .collect(Collectors.toList());

        int index = numberList.indexOf(target);

        if (index != -1) {
            System.out.println("Element " + target + " found at index " + index);
        } else {
            System.out.println("Element " + target + " not found in the array");
        }

    }

}

This approach uses Java’s Arrays class to convert the array to a list and then find the index of the target element. It’s useful for beginners to see how built-in utilities can save time while achieving the same result. It also introduces modern Java practices like streams and conversions.

Program 6: Linear Search for Strings

Linear Search is not limited to numbers. This program demonstrates searching for a string in an array of words, which is useful for applications like searching names, cities, or other textual data.

public class LinearSearchStrings {

    public static int linearSearch(String[] arr, String key) {

        for (int i = 0; i < arr.length; i++) {

            if (arr[i].equals(key)) {
                return i;
            }

        }

        return -1; // Element not found

    }

    public static void main(String[] args) {

        String[] names = {"Harry", "Hermione", "Ron", "Luna", "Neville"};
        String key = "Luna";

        System.out.println("Array Elements:");

        for (String name : names) {
            System.out.print(name + " ");
        }

        System.out.println();

        int result = linearSearch(names, key);

        if (result == -1) {
            System.out.println("Name " + key + " not found in the array.");
        } else {
            System.out.println("Name " + key + " found at index " + result + ".");
        }

    }

}

Here, we use the .equals() method to compare strings. This shows beginners that Linear Search can be applied to any data type, as long as elements can be compared for equality.

Frequently Asked Questions (FAQ)

Linear search is simple, but beginners often have questions about when and why to use it. Here are some common queries with clear explanations.

Q1: What is linear search used for?
Linear search is used to find a specific element in an array or list. It is most effective for small or unsorted datasets.

Q2: Is linear search efficient?
Linear search is simple but not efficient for large datasets because it checks each element one by one. More advanced algorithms, like binary search, are faster for sorted data.

Q3: Can linear search work with strings?
Yes, linear search can be applied to strings, characters, or any data type in Java. The logic remains the same: check each element sequentially.

Q4: Why learn recursion for linear search?
Recursion is a different way of solving problems. It strengthens understanding of functions and introduces new ways to approach programming challenges.

Q5: Are built-in Java methods better than manual search?
Built-in methods like indexOf can simplify coding, but knowing how to implement linear search manually is important for learning programming fundamentals.

Conclusion

Linear search is a foundational concept that every beginner should understand. By implementing it in Java using loops, functions, recursion, and built-in utilities, you gain versatile problem-solving skills. Each approach demonstrates different aspects of programming, from iterative thinking to recursive logic and practical use of Java libraries.

Practicing these programs will make you comfortable with array traversal, conditional checks, and method creation. Start with simple loops, explore recursion, and then use built-in methods to save time. The more you experiment, the stronger your foundation will be for learning advanced searching and sorting algorithms in Java.

Scroll to Top