# Perform Binary Search in Java using Collections.binarySearch

Java 8Object Oriented ProgrammingProgramming

Binary Search can be performed in Java using the method java.util.Collections.binarySearch(). This method requires two parameters i.e. the list in which binary search is to be performed and the element that is to be searched. It returns the index of the element if it is in the list and returns -1 if it is not in the list.

A program that demonstrates this is given as follows −

## Example

Live Demo

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Demo {
public static void main(String args[]) {
List aList = new ArrayList();
Collections.sort(aList);
System.out.println("The sorted ArrayList is: " + aList);
int index = Collections.binarySearch(aList, "Martha");
System.out.println("Element Martha is at index: " + index);
index = Collections.binarySearch(aList, "Amy");
System.out.println("Element Amy is at index: " + index);
}
}

The output of the above program is as follows −

The sorted ArrayList is: [Bruce, George, James, Martha, Susan]
Element Martha is at index: 3
Element Amy is at index: -1

Now let us understand the above program.

The ArrayList aList is created. Then ArrayList.add() is used to add the elements to the ArrayList. The ArrayList elements are sorted using Collections.sort(). A code snippet which demonstrates this is as follows −

List aList = new ArrayList();
Collections.sort(aList);
System.out.println("The sorted ArrayList is: " + aList);
System.out.println("Element Amy is at index: " + index);