Java Arrays.binarySearch() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.Arrays

Definition

In Java, Arrays.binarySearch(a, key) searches a sorted array by repeatedly halving the part that could contain key. It needs about log2(n) comparisons, so even a million elements take only about 20 steps.

If the key is found, the result is its index. If not, the result is negative: -(insertionPoint) - 1, where the insertion point is the index at which the key would have to be inserted to keep the array sorted. The - 1 makes sure "not found" is never 0.

A static method of java.util.Arrays (Java 1.2+): call it on the class, as in Arrays.binarySearch(...); there is no Arrays object to create. The range overloads were added in Java 6.

Syntax

Sort first, then search the whole array or a range.

Java
int[] a = {10, 20, 30, 40};            // must be sorted
int i = Arrays.binarySearch(a, 30);     // 2
int j = Arrays.binarySearch(a, 25);     // -3  (insertion point 2)
int k = Arrays.binarySearch(a, 1, 3, 40); // -4 (searches indexes 1 and 2)
CallWhat it does
Arrays.binarySearch(a, key)Search the whole sorted array.
Arrays.binarySearch(a, from, to, key)Search indexes from to to - 1 only.
Arrays.binarySearch(objs, key, comparator)Search an array sorted by that comparator.
-result - 1Turns a negative result back into the insertion point.

The pair (a, key) and (a, from, to, key) exists for int, long, short, char, byte, float, double, and Object arrays; the Comparator versions exist for T[].

Library declarations
Java
// java.util.Arrays (since Java 1.2; ranges since Java 6)
public static int binarySearch(int[] a, int key)
public static int binarySearch(int[] a, int fromIndex, int toIndex, int key)
public static int binarySearch(Object[] a, Object key)
public static <T> int binarySearch(T[] a, T key, Comparator<? super T> c)
public static <T> int binarySearch(T[] a, int fromIndex, int toIndex, T key, Comparator<? super T> c)
// same pair for long[], short[], char[], byte[], float[], double[]

Parameters

ParameterDescription
aThe array to search, sorted in ascending order (or by c).
fromIndex, toIndex (optional)Range to search: fromIndex inclusive, toIndex exclusive.
keyThe value to find.
c (optional)The comparator the array was sorted with.

Return Value

Return ValueDescription
int ≥ 0The index of an element equal to key.
int < 0-(insertionPoint) - 1; the insertion point is the index of the first larger element, or a.length (or toIndex) if all are smaller.

Compare with Similar Methods

Other ways to find a value:

MethodHow it differs
Arrays.sort(a)Run it first; binary search only works on sorted data.
a simple loopWorks on unsorted arrays, but checks elements one by one.
Arrays.mismatch(a, b)Finds where two arrays first differ (Java 9).
list.indexOf(o)Linear search in an ArrayList; no sorting needed.

Java Examples

Example 1 — Find a Score and an Insertion Point

Look up a score that exists and one that does not, and decode the negative result.

Java
import java.util.Arrays;

public class ArraysBinarySearchDemo {
    public static void main(String[] args) {
        int[] scores = {12, 25, 38, 47, 59, 63};

        int found = Arrays.binarySearch(scores, 47);
        System.out.println("47 at index " + found);

        int missing = Arrays.binarySearch(scores, 50);
        int insertAt = -missing - 1;
        System.out.println("50 -> " + missing + ", would go at index " + insertAt);
    }
}

How It Works

  1. Sorted input. The scores are already in ascending order, which binary search requires.
  2. A hit. 47 is at index 3, so that index is returned directly.
  3. A miss. 50 would belong between 47 and 59, at index 4, so the method returns -(4) - 1 = -5.
  4. Decode it. -missing - 1 turns -5 back into 4, the index where 50 could be inserted to keep the order.

Example 2 — Sort a String Array Before Searching

Fruit names arrive unsorted; sort them, then search for one present and one missing name.

Java
import java.util.Arrays;

public class ArraysBinarySearchSortFirst {
    public static void main(String[] args) {
        String[] fruits = {"pear", "apple", "mango", "kiwi", "banana"};
        Arrays.sort(fruits);
        System.out.println("sorted: " + Arrays.toString(fruits));

        System.out.println("kiwi: " + Arrays.binarySearch(fruits, "kiwi"));
        System.out.println("fig:  " + Arrays.binarySearch(fruits, "fig"));
    }
}

How It Works

  1. Sort first. The original order (pear, apple, ...) is not sorted, so Arrays.sort runs before any search.
  2. Strings compare alphabetically. The object overload uses compareTo, and kiwi lands at index 2.
  3. Where fig would go. "fig" comes after "banana" and before "kiwi", so its insertion point is 2 and the result is -3.
  4. Search the same order you sorted. Sorting with natural order and searching with natural order keeps the two consistent.

Example 3 — Search a Descending Array and a Range

Use the same comparator the array was sorted with, then search part of an int[].

Java
import java.util.Arrays;
import java.util.Collections;

public class ArraysBinarySearchComparator {
    public static void main(String[] args) {
        Integer[] desc = {90, 75, 60, 45, 30};
        int i = Arrays.binarySearch(desc, 60, Collections.reverseOrder());
        System.out.println("60 in descending array: index " + i);

        int[] ids = {3, 8, 15, 21, 34, 55};
        System.out.println("21 in [1, 4): " + Arrays.binarySearch(ids, 1, 4, 21));
        System.out.println("55 in [1, 4): " + Arrays.binarySearch(ids, 1, 4, 55));
    }
}

How It Works

  1. Match the sort order. desc runs from large to small, so the search must use Collections.reverseOrder(); plain natural order would give a wrong answer.
  2. Absolute indexes. The range search looks only at indexes 1 to 3 (8, 15, 21), but it reports 21 at index 3 of the whole array.
  3. Outside the range. 55 exists at index 5, but that index is not searched, so it counts as missing.
  4. Insertion point at toIndex. 55 is larger than everything in the range, so its insertion point is 4 and the result is -(4) - 1 = -5.

Frequently Asked Questions

Yes. On an unsorted array the result is unspecified and may be wrong. Call Arrays.sort first, using the same order you will search with.
The key was not found. The value is -(insertionPoint) - 1, so -result - 1 gives the index where the key would be inserted.
Any one of them; the documentation does not guarantee the first or the last.
It halves the search range at every step, so it needs about log2(n) comparisons instead of up to n.
Yes. Arrays.binarySearch(a, fromIndex, toIndex, key) searches indexes fromIndex to toIndex - 1 and returns an index in the whole array.

Next: Arrays.compare()

Order two arrays lexicographically: negative, zero, or positive (Java 9).

compare() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful