Arrays Utility Class

The Arrays utility class collects common array operations in one place.

MethodPurpose
sort(array)Sort the array in place
binarySearch(array, value)Find a value in a sorted array
copyOf(array, length)Create a resized copy
equals(first, second)Compare element values
toString(array)Format elements for display

binarySearch is fast because it repeatedly discards half the search range, but that logic requires sorted input.

Sort before searching

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] ids = {40, 10, 30};
        Arrays.sort(ids);
        int result = Arrays.binarySearch(ids, 25);
        System.out.println(Arrays.toString(ids));
        System.out.println(result < 0);
    }
}

Output:

[10, 30, 40]
true

The sorted array does not contain 25, so the search result is negative. The comparison turns that detail into a clear found-or-not-found answer.

When a target is absent, binarySearch returns a negative insertion-point encoding, not simply -1. Check for a result below zero.

Sort the values before binarySearch, then print the sorted array and target index.