← Back to list

Linear Search Algorithm in Java: Learn with Practical Examples

Linear Search is one of the simplest and most fundamental searching algorithms in computer science. Unlike more advanced techniques such as…

Robin Viktorsson · 2026-05-02 17:31 · 0 claps · 8.5 min read
#java #programming #linear-search #algorithms #tutorial
Open on Medium ↗
Wiki topics: 💻 · Programming 🔬 · Science · General

Linear Search Algorithm in Java: Learn with Practical Examples

Linear Search is one of the simplest and most fundamental searching algorithms in computer science. Unlike more advanced techniques such as binary search or interpolation search, it does not depend on sorted data or complex logic. Instead, it follows a direct approach: it checks each element one by one until the target value is found or the dataset ends.

Although it is not the most efficient algorithm in terms of performance, its clarity and ease of implementation make it an important foundation for learning how search algorithms work. It also helps build intuition for how more advanced techniques improve upon this basic idea.

In this article, we’ll explore how Linear Search works, implement it in Java, and examine both its strengths and its limitations in real-world scenarios.

What Is Linear Search? 🔍

Linear Search (also known as sequential search) is one of the first searching techniques developers learn in computer science. It is a basic algorithm used to find a target value within a list or array, and it introduces the fundamental idea of searching by inspection.

It works by iterating through each element from start to finish until the desired value is found or the entire list has been checked.

Here’s the core idea:

  • Start from the first element
  • Compare it with the target
  • If equal → done
  • If not → move to the next element
  • Repeat until the element is found or the list ends

You can think of it like looking for a name in an unsorted contact list — you go through each entry one by one until you find what you’re looking for.

When Should You Use Linear Search? 🧐

Linear search makes the most sense in situations where simplicity and flexibility matter more than raw speed. It works especially well when the dataset is small, because checking each element one by one doesn’t take much time anyway. It’s also a natural fit when the data isn’t sorted and you don’t want the extra overhead of organizing it first.

Another good use case is when you only need to perform a single search. If you’re not going to reuse the data structure repeatedly, spending time sorting or indexing can actually cost more effort than just scanning through the data once. In those moments, linear search is often the more practical option.

Its performance varies depending on where the target appears. In the best case, when the element is the very first one checked, the time complexity is O(1), meaning the result is found immediately. In the worst case, when the element is at the end of the dataset or not present at all, the time complexity becomes O(n), since every element must be examined. This linear growth in runtime is exactly why the algorithm doesn’t scale well for large datasets.

Even so, in real-world scenarios where data is modest in size or constantly changing, linear search remains a reliable and straightforward solution.

From Theory to Practice 🛠️

Before implementing Linear Search manually, it’s worth noting that Java provides built-in methods like contains() for collections. In sequential collections such as ArrayList or LinkedList, this method internally performs a linear search. Understanding this helps you make more informed decisions about when simplicity is sufficient and when a different data structure might offer better performance.

1. Core Implementation (Iterative)

Let’s start with a basic iterative implementation of Linear Search in Java. This is the most common and beginner-friendly way to understand how the algorithm works in practice.

public class Main {

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

        // Traverse the array element by element
        for (int i = 0; i < arr.length; i++) {

            // Check if current element matches target
            if (arr[i] == target) {
                return i;
            }
        }

        // Target not found
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {4, 2, 7, 1, 9, 3};

        int result = linearSearch(arr, 7);

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

// Output:
// Element found at index: 2

This implementation demonstrates the most direct form of Linear Search: a simple traversal of the array from start to finish. The algorithm begins at index 0 and checks each element one by one, comparing it to the target value. If a match is found, it immediately returns the current index, which also stops further execution early.

If the loop completes without finding the target, the method returns -1 to indicate that the element is not present in the array.

What makes this approach so important is its simplicity. There is no need for additional data structures, no recursion, and no requirement for the array to be sorted. The logic relies entirely on a single loop and direct comparison, making it easy to read, debug, and understand.

2. Recursive Implementation

Although less common in practice, Linear Search can also be implemented using recursion. This version helps illustrate how the same problem can be solved by breaking it down into smaller subproblems, where each recursive call handles a single element.

public class Main {

    public static int linearSearch(int[] arr, int target, int index) {

        // Base case: reached end of array
        if (index >= arr.length) {
            return -1;
        }

        // Check current element
        if (arr[index] == target) {
            return index;
        }

        // Recursive call for next index
        return linearSearch(arr, target, index + 1);
    }

    public static void main(String[] args) {
        int[] arr = {4, 2, 7, 1, 9, 3};

        int result = linearSearch(arr, 7, 0);

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

// Output:
// Element found at index: 2

In this recursive version, the algorithm starts at index 0 and checks one element at a time. Each function call is responsible for evaluating a single position in the array. If the current element matches the target, the function immediately returns the index. If not, it calls itself again with the next index, effectively moving forward through the array step by step.

The recursion stops when either the target is found or the index goes beyond the last element, which serves as the base case.

While this approach is useful for understanding how recursion works, it is generally less practical than the iterative version. Each recursive call adds overhead to the call stack, which can impact performance and memory usage, especially for large arrays. For this reason, the iterative implementation is preferred in most real-world applications, even though both versions have the same O(n) time complexity.

3. Linear Search with Objects

Linear Search is not limited to primitive data types like integers — it can also be applied to objects. This makes it especially useful in real-world applications where data is usually stored in structured forms such as classes and collections.

In this example, we define a simple Product class and perform a search based on a property (name).

import java.util.*;

class Product {
    String name;
    double price;
    Product(String name, double price) {
        this.name = name;
        this.price = price;
    }
}
public class Main {
    public static int linearSearch(List<Product> list, String targetName) {
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).name.equals(targetName)) {
                return i;
            }
        }
        return -1;
    }
    public static void main(String[] args) {
        List<Product> products = new ArrayList<>();
        products.add(new Product("Book", 12.99));
        products.add(new Product("Laptop", 999.99));
        products.add(new Product("Pen", 1.49));
        products.add(new Product("Phone", 599.99));

        int index = linearSearch(products, "Phone");

        if (index != -1) {
            System.out.println("Found: " + products.get(index).name);
        } else {
            System.out.println("Not found");
        }
    }
}

// Output:
// Found: Phone

In this version, Linear Search is applied to a list of objects instead of simple values. The algorithm iterates through each Product in the list and compares the name field with the target value. If a match is found, it returns the index of that object in the list.

This demonstrates an important concept: Linear Search is not tied to a specific data type. It can operate on any structure as long as you can define a comparison condition.

One of the key advantages here is that no sorting or pre-processing is required. You can search based on any property — such as name, price, or ID — without modifying the underlying data structure. This makes Linear Search particularly useful in dynamic systems where objects are frequently added, removed, or updated.

Its flexibility allows it to work with arrays, lists, and complex objects alike, without requiring random access or any special constraints. However, this flexibility comes with a trade-off. As the dataset grows, performance becomes a limitation because Linear Search must examine each element individually and cannot skip or optimize based on structure.

Where Linear Search Becomes Useful 💡

Despite its simplicity, Linear Search appears in many practical scenarios where its straightforward behavior is actually an advantage rather than a limitation.

1. Small Datasets and Quick Checks

When working with small collections, the performance difference between Linear Search and more advanced algorithms is often negligible. In such cases, the overhead of more complex solutions is not justified, and a simple scan is usually the most practical approach.

public class Main {

    public static boolean contains(int[] arr, int target) {
        for (int num : arr) {
            if (num == target) return true;
        }

        return false;
    }

    public static void main(String[] args) {
        int[] values = {5, 8, 12, 20};

        System.out.println(contains(values, 12));
    }
}

// Output:
// true

In situations like this, simplicity is more valuable than optimization.

2. Unsorted or dynamic data

In systems where data changes frequently, maintaining a sorted structure can be expensive and impractical. Inserts, deletions, and updates would constantly require reordering or restructuring.

Linear Search avoids this entirely by operating directly on the raw data, without any preprocessing requirements. This makes it a natural fit for dynamic datasets where the content is continuously evolving.

import java.util.*;

public class Main {

    public static boolean contains(List<Integer> list, int target) {

        for (int value : list) {
            if (value == target) return true;
        }

        return false;
    }

    public static void main(String[] args) {

        List<Integer> numbers = new ArrayList<>();
        numbers.add(10);
        numbers.add(25);
        numbers.add(7);
        numbers.add(30);

        System.out.println(contains(numbers, 7));
    }
}

// Output:
// true

3. Streaming and real-time data

When working with streaming data such as logs, sensor readings, or live event feeds, sorting the data beforehand is often not possible or would introduce unacceptable delay.

Linear Search works well here because it allows immediate processing: each incoming value can be checked on the spot, and actions can be triggered instantly based on the result.

public class Main {

    public static void processStream(int[] stream, int target) {

        for (int value : stream) {
            if (value == target) {
                System.out.println("Target found: " + value);
                return;
            }
        }

        System.out.println("Target not found in stream.");
    }

    public static void main(String[] args) {

        int[] sensorData = {3, 15, 8, 22, 5};

        processStream(sensorData, 22);
    }
}

// Output:
// Target found: 22

4. Fallback mechanism

Even in systems that primarily rely on more advanced search techniques, Linear Search often serves as a reliable fallback when the dataset is small, the structure is unknown, or edge cases need a simple and predictable solution. It acts as a safe default when no assumptions can be made about the data.

Conclusion 📣

Linear Search may be one of the simplest algorithms in computer science, but its value lies precisely in that simplicity. By checking each element sequentially, it avoids any dependency on sorting, indexing, or specialized data structures, making it easy to understand, implement, and apply in a wide range of scenarios.

Throughout this article, we saw that Linear Search performs reliably across both primitive data types and objects, whether implemented iteratively or recursively. In Java, it is also closely reflected in built-in methods like contains(), which often rely on the same underlying idea depending on the collection type. This connection reinforces an important lesson: even high-level abstractions are frequently built on fundamental algorithms like linear search.

At the same time, we also learned its limitations. With a time complexity of O(n) in the worst case, Linear Search does not scale efficiently for large datasets. It cannot exploit structure in the data or reduce the search space, which is why more advanced algorithms become necessary as performance demands increase.

However, this does not diminish its importance. In fact, Linear Search remains highly relevant in real-world development — especially when working with small datasets, dynamic or frequently changing data, real-time streams, or as a dependable fallback when no assumptions can be made about structure or ordering.

Ultimately, Linear Search serves as a foundational concept: it builds intuition for algorithmic thinking and provides a baseline for understanding why more advanced search techniques exist. Mastering it is not about performance optimization, but about developing a clear understanding of how searching works at its most fundamental level.

Happy coding! 😃

🙏 Thanks for reading to the end! If you have any questions, feel free to drop a comment below.

If you enjoyed this article, follow me on medium or social media — I’d love to connect and follow you back:


메타데이터
post_id
491adb91bb1f
slug
linear-search-algorithm-in-java-learn-with-practical-examples-491adb91bb1f
url
https://medium.com/@robinviktorsson/linear-search-algorithm-in-java-learn-with-practical-examples-491adb91bb1f
canonical_url
https://medium.com/@robinviktorsson/linear-search-algorithm-in-java-learn-with-practical-examples-491adb91bb1f
author_url
https://medium.com/@robinviktorsson
status
ok
fetched_at
2026-08-12 19:20:28