Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Linear search in Java

Last updated: 29 Sept 20264 min read
guide
By AITrove Editorial

Linear search examines elements in sequence until a match is found or the complete search range has been exhausted.

Implementation

Java
static int find(int[] values, int target) {
    for (int i = 0; i < values.length; i++) {
        if (values[i] == target) return i;
    }
    return -1;
}

Reasoning

In the worst case every element is checked, so time grows linearly with array length. Extra space stays constant. This version assumes a non-null array.

Check

Try a target at the first position, at the last position and a missing target.

Specify which match is returned

The existing method returns the first matching index. Repeated values do not change that rule. A last-match search must continue after finding an earlier occurrence, while a count-of-matches API must retain a counter rather than return an index.

Minus one represents absence because valid array indexes are non-negative. Returning zero for absence would collide with a real match in the first position. An API returning an object instead needs an explicit missing-value representation, such as Optional, rather than borrowing an unrelated numeric sentinel.

An empty array has no match and executes no loop iterations. A null array is outside this implementation’s input contract and fails before a scan can begin. Put validation at the boundary if callers need a named exception for missing input.

Use the simple scan as a reference

For small test fixtures, a linear scan is a useful reference against which to check a more elaborate index. Compare the actual membership and first-position semantics. A faster method that returns a different duplicate occurrence is not interchangeable when the caller requires the first one.

The best case inspects one element, while absence or a match at the final position requires n comparisons. Extra working storage is O(1). For repeated searches, building a hash index may reduce lookup work but adds storage and changes update costs.

Binary search requires sorted input and has separate duplicate-position choices. Sorting a batch only to answer one lookup may cost more than this scan; include that preprocessing rather than comparing the scan with only the binary-search loop.

Common Mistakes

Check empty inputs and invalid values before applying this operation to application data. State whether a method edits shared state or returns a separate value.

java-dsa
Storage details