Join our newsletter for the latest updates.

Java binarySearch()

In Java, the binarySearch() method of the collections framework can be used to search a specified element in a collection.

The binarySearch() method implements the binary search algorithm to search the element passed as an argument. If you want to learn about how binary search works, visit Binary search algorithm.

Note: If we need to implement the binary search algorithm in Java, it is better to use the binarySearch() method rather than implementing the algorithm on our own.

Example: Java binarySearch()

import java.util.ArrayList;
import java.util.Collections;

class Main {
    public static void main(String[] args) {

        // Creating an array list
        ArrayList<Integer> numbers = new ArrayList<>();

        // Add elements
        System.out.println("ArrayList: " + numbers);

        // Using the binarySearch() method
        int position = Collections.binarySearch(numbers, 3);
        System.out.println("Position of 3: " + position);


ArrayList: [2, 3, 4]
Position of 3: 1