Java Collection Tutorial - Java Arrays.binarySearch(Object [] a, int fromIndex, int toIndex, Object key)








Syntax

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

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

Example

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

Binary search needs sorted arrays.

//from   www .  jav  a2  s . c  o  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;

    // entering range of index
    int retVal = Arrays.binarySearch(arr,2,4,searchVal);

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

The code above generates the following result.