Java Collection Tutorial - Java Arrays.binarySearch(long[] a, long key)








Syntax

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

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

Example

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

Binary search needs sorted arrays.

/*from w w  w  . j a  v a 2  s.  c om*/


import java.util.Arrays;

public class Main {

   public static void main(String[] args) {

    // initializing sorted long array
    long longArr[] = {123456789L,1123456789L,2123456789L,3123456789L,4123456789L};

    // value to search
    long searchVal = 2123456789L;

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

    System.out.println(retVal);
  }
}

The code above generates the following result.