Arrays ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-07-16

Method Arrays.binarySearch()

The Arrays.binarySearch() method from the java.util.Arrays class performs a binary search in a sorted array and returns the index of the specified value. If the element is not found, the method returns a negative number equal to -(insertionPoint) - 1, where the insertion point is the index at which the value would be inserted to keep the array sorted. The key requirement: the array must be sorted in ascending order before the call — otherwise the result is undefined.

How Arrays.binarySearch() Works

On each step, binary search compares the target value with the element in the middle of the array and discards the half that cannot contain the value. That is why binarySearch in Java finds an element in O(log n) comparisons — an array of a million elements takes roughly 20 steps, while a linear scan would need up to a million.

import java.util.Arrays;

public class BinarySearchExample1 {
    public static void main(String[] args) {
        int[] array1 = {10, 20, 30, 40};
        int pos1 = Arrays.binarySearch(array1, 20);
        int pos2 = Arrays.binarySearch(array1, 25);
        System.out.println(pos1);
        System.out.println(pos2);
    }
}

Output:

1
-3

The value 20 is found at index 1. The value 25, however, is not in the array — and this is where the interesting part begins.

Important

Before calling Arrays.binarySearch(), the array must be sorted in ascending order (usually with Arrays.sort()). For an unsorted array the method does not throw an exception — it simply returns a meaningless result, and this kind of bug is easy to miss.

What binarySearch Returns When the Element Is Not Found

A negative result is not just a "failure flag" — it carries useful information. The formula is -(insertionPoint) - 1, where the insertion point is the index of the first element greater than the search key. In the example above, the value 25 would belong at position 2 (between 20 and 30), so the method returned -(2) - 1 = -3.

The insertion point is easy to recover from the negative result — handy when you want to insert the element while keeping the array sorted:

int result = Arrays.binarySearch(array1, 25); // -3
if (result < 0) {
    int insertionPoint = -result - 1;         // 2
    System.out.println("Insert at position: " + insertionPoint);
}

The extra offset of one exists to distinguish "not found, insertion point 0" (result -1) from "found at index 0" (result 0).

Overloads of Arrays.binarySearch()

The Arrays class provides binarySearch overloads for all numeric primitives (int, long, double, and others), for char, and for object arrays. The full list is in the official Oracle documentation.

Overload Where it searches How it compares
binarySearch(int[] a, int key) The whole primitive array Numeric comparison
binarySearch(int[] a, int from, int to, int key) Index range [from, to) Numeric comparison
binarySearch(Object[] a, Object key) The whole object array Natural ordering (Comparable)
binarySearch(T[] a, T key, Comparator<? super T> c) The whole object array The given Comparator

The overload with fromIndex and toIndex parameters searches only within the specified range: the start index is inclusive, the end index is exclusive. It is this range that must be sorted:

import java.util.Arrays;

public class BinarySearchExample2 {
    public static void main(String[] args) {
        int[] array = {5, 10, 15, 20, 25, 30};
        // Search for 20 only among indices 1, 2, and 3
        int pos = Arrays.binarySearch(array, 1, 4, 20);
        System.out.println(pos); // 3
    }
}

Searching Object Arrays with a Comparator

For object arrays without a comparator, the natural ordering is used — the elements must implement the Comparable interface, as String and Integer do:

import java.util.Arrays;

public class BinarySearchExample3 {
    public static void main(String[] args) {
        String[] names = {"Anna", "Boris", "Ivan", "Olga"};
        int pos = Arrays.binarySearch(names, "Ivan");
        System.out.println(pos); // 2
    }
}

If the array is sorted in a non-natural order (for example, descending), you must pass the same Comparator that was used for sorting:

import java.util.Arrays;
import java.util.Comparator;

public class BinarySearchExample4 {
    public static void main(String[] args) {
        Integer[] numbers = {40, 30, 20, 10};
        int pos = Arrays.binarySearch(numbers, 20, Comparator.reverseOrder());
        System.out.println(pos); // 2
    }
}

Common Mistakes with binarySearch

  • Unsorted array. The method does not verify the element order — that would be expensive. It simply runs the algorithm and may return a negative number even for an element that is present in the array.
  • Duplicates. If the search key occurs multiple times, there is no guarantee which of the matching indices is returned — not necessarily the first one.
  • Comparator does not match the sort order. An array sorted in descending order cannot be searched with the comparator-less overload — the search must use the same rule the array was ordered by.
  • Comparing the result to -1. The check if (result == -1) catches only the "insertion point 0" case. The correct "not found" check is result < 0.
  • null and objects without Comparable. Searching for null, or for objects that do not implement Comparable (with the comparator-less overload), leads to a NullPointerException or ClassCastException.

Frequently Asked Questions

What does Arrays.binarySearch() return if the element is not found?

A negative number computed as minus the insertion point minus one. The insertion point is the index where the element could be inserted while keeping the array sorted. You can recover it with -result - 1.

What happens if I call binarySearch on an unsorted array?

The result is undefined: no exception is thrown, but the method may "miss" an element that exists or return an arbitrary index. Sort the array first, for example with Arrays.sort().

Which index does binarySearch return if the array contains duplicates?

Any of the indices where the search key is found — the specification does not guarantee the first occurrence. If you need exactly the first or the last duplicate, you have to implement the binary search yourself.

How is Arrays.binarySearch() different from Collections.binarySearch()?

The algorithm is the same; the data structures differ: Arrays.binarySearch() works with arrays, while Collections.binarySearch() works with lists (List). Both require the data to be sorted in ascending order.

Comments

Please log in or register to have a possibility to add comment.