How to Find the Index of a Given Element in an Array in Java

Finding the index of an element is one of the most common operations performed on arrays. Unlike String and ArrayList, Java arrays do not provide a built-in indexOf() method. Instead, you must search the array yourself or use utility methods such as Arrays.binarySearch() when appropriate.

In this tutorial, you'll learn several ways to find an element's index in a Java array, including Linear Search, Binary Search, Java Streams, and how to find all occurrences of a repeated element.


Problem Statement

Given the following array:

Advertisement
 
int[] numbers = {10, 25, 30, 45, 30};
 

Find the index (or indexes) of the target value:

 
int target = 30;
 

Output

 
First occurrence : 2
All occurrences  : [2, 4]
 

Method 1: Linear Search (Works on Any Array)

Linear Search checks each element one by one until the target value is found.

Example

 
public class Main {

    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 = {10, 25, 30, 45, 30};

        int index = linearSearch(numbers, 30);

        System.out.println("Index: " + index);
    }
}
 

Output

 
Index: 2
 

Explanation

The algorithm starts from the first element and compares each value with the target.

  • If a match is found, its index is returned immediately.
  • If no match exists, -1 is returned.

This method works for:

  • Sorted arrays
  • Unsorted arrays
  • Arrays containing duplicate values

Time Complexity: O(n)

Space Complexity: O(1)


Method 2: Binary Search (Sorted Arrays Only)

Binary Search is much faster but requires the array to be sorted.

Example

 
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {

        int[] numbers = {10, 25, 30, 40, 45};

        int index = Arrays.binarySearch(numbers, 30);

        System.out.println("Index: " + index);
    }
}
 

Output

 
Index: 2
 

Explanation

Arrays.binarySearch() repeatedly divides the search range into two halves until the target is found.

Because the array is sorted, it can eliminate half of the remaining elements after every comparison.

Time Complexity: O(log n)

Space Complexity: O(1)

Important: Never use Arrays.binarySearch() on an unsorted array. The result is unpredictable and should not be relied upon.


Method 3: Using Java Streams

Java Streams provide a concise and modern approach to finding an element's index.

Example

 
import java.util.stream.IntStream;

public class Main {

    public static void main(String[] args) {

        int[] numbers = {10, 25, 30, 45, 30};

        int target = 30;

        int index = IntStream.range(0, numbers.length)
                .filter(i -> numbers[i] == target)
                .findFirst()
                .orElse(-1);

        System.out.println("Index: " + index);
    }
}
 

Output

 
Index: 2
 

Explanation

  • IntStream.range() generates all valid array indexes.
  • filter() keeps only the indexes where the value matches the target.
  • findFirst() returns the first matching index.
  • orElse(-1) returns -1 if the value is not found.

Time Complexity: O(n)

Space Complexity: O(1)


Finding All Indexes of a Repeated Element

Sometimes the same value appears multiple times in an array.

Instead of stopping after the first match, collect every matching index.

Example

 
import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        int[] numbers = {10, 25, 30, 45, 30};

        int target = 30;

        List<Integer> indexes = new ArrayList<>();

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

            if (numbers[i] == target) {
                indexes.add(i);
            }
        }

        System.out.println(indexes);
    }
}
 

Output

 
[2, 4]
 

This approach scans the entire array and stores every matching index.


Step-by-Step Explanation

Given:

 
[10, 25, 30, 45, 30]
 

Target:

 
30
 

Step 1

Compare:

 
10 == 30
 

Not equal.


Step 2

Compare:

 
25 == 30
 

Not equal.


Step 3

Compare:

 
30 == 30
 

Match found.

Return index:

 
2
 

The search stops immediately after finding the first occurrence.


Given the sorted array:

 
[10, 25, 30, 40, 45]
 

Initial values:

 
low = 0
high = 4
 

Middle index:

 
mid = (0 + 4) / 2 = 2
 

Element:

 
numbers[2] = 30
 

Since it matches the target, Binary Search returns index 2 immediately.


Internal Working

Linear Search

 
Index 0 → 10 ❌
Index 1 → 25 ❌
Index 2 → 30 ✅
 

Search stops after the first match.


Binary Search

 
low = 0
high = 4
mid = 2

numbers[2] = 30
 

The target is found in a single comparison because it happens to be the middle element.

Binary Search repeatedly reduces the search space by half, making it much faster for large sorted arrays.


Real-Life Analogy

Imagine searching for a person's name in a phone directory.

Linear Search is like reading every name from the first page until you find the person.

Binary Search is like opening the directory near the middle, checking whether the name should appear before or after that page, and repeatedly narrowing the search until the correct page is reached.

Binary Search is much faster, but it only works because the phone directory is already sorted alphabetically.


Best Practices

  • Use Linear Search for unsorted arrays.
  • Use Binary Search only on sorted arrays.
  • Use Java Streams for concise and readable code.
  • Use a List<Integer> when multiple occurrences need to be returned.
  • Return -1 when the target is not found.

Common Mistakes

1. Using Binary Search on an Unsorted Array

Incorrect:

 
Arrays.binarySearch(numbers, 30);
 

if the array is unsorted.

Binary Search requires sorted data.


2. Assuming Arrays Have indexOf()

Java arrays do not provide:

 
numbers.indexOf(30);
 

You must implement searching manually or use utility methods.


3. Returning Only the First Match

If duplicates exist and the problem requires every occurrence, continue searching instead of returning immediately.


4. Misunderstanding Negative Return Values

When Arrays.binarySearch() does not find the element, it returns a negative value.

That value represents the insertion point rather than simply indicating "not found."


Expert Tips

  • Arrays.binarySearch() returns -(insertionPoint) - 1 when the target is missing.
  • If you'll search the same array many times, sorting once and using Binary Search can improve overall performance.
  • For very frequent lookups, consider building a HashMap<Integer, List<Integer>> that stores each value and all of its indexes.
  • Binary Search is one of the most frequently asked algorithms in technical interviews.

Comparison Table

Method Time Complexity Requires Sorted Array? Finds All Occurrences?
Linear Search O(n) ❌ No ✅ Yes (with modification)
Binary Search O(log n) ✅ Yes ❌ No
Java Streams O(n) ❌ No ✅ Yes (with modification)
HashMap (Preprocessed) O(1) Average Lookup* ❌ No ✅ Yes

*After an initial O(n) preprocessing step.


Frequently Asked Questions

1. Do Java arrays have an indexOf() method?

No. Unlike String and ArrayList, Java arrays do not provide an indexOf() method.


2. Can I use Arrays.binarySearch() on an unsorted array?

No. Binary Search only works correctly on sorted arrays.


3. What does a negative return value from Arrays.binarySearch() mean?

It indicates that the element was not found and encodes the insertion point where the element would be inserted to maintain sorted order.


4. Which search algorithm is faster?

Binary Search is much faster (O(log n)) than Linear Search (O(n)), but only for sorted arrays.


5. How can I find every occurrence of a repeated value?

Use Linear Search and store every matching index in a List<Integer>.


Usually no. Sorting costs O(n log n), which is more expensive than a single Linear Search. Sorting becomes beneficial only when performing many searches.


7. Can Java Streams find an element's index?

Yes. IntStream.range() combined with filter() and findFirst() provides a concise solution.


8. How do I find an element in a 2D array?

Use nested loops to iterate through each row and column until the target is found.