Java Arrays.binarySearch(Object [] a, Object key)

Syntax

Arrays.binarySearch(Object [] a, Object key) has the following syntax.

public static int binarySearch(Object [] a,   Object key)

Example

In the following code shows how to use Arrays.binarySearch(Object [] a, Object key) method.

Binary search needs sorted arrays.


//  w w  w.  ja v  a 2 s.co  m
import java.util.Arrays;

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

    // initializing sorted array
    Object arr[] = {1,2,22,69,111,222};

    // value to search
    int searchVal = 22;

    int retVal = Arrays.binarySearch(arr,searchVal);

    System.out.println("The index of element 22 is : " + retVal);
  }
}

The code above generates the following result.