OCA Java SE 8 Core Java APIs - OCA Mock Question Core Java APIs 2-6








Question

What is the result of the following?

public class Main{
   public static void main(String[] argv){
         List<String> hex = Arrays.asList("10", "8", "4B", "FF"); 
         Collections.sort(hex); 
         
         int x = Collections.binarySearch(hex, "8"); 
         int y = Collections.binarySearch(hex, "4B"); 
         int z = Collections.binarySearch(hex, "4F"); 
         System.out.println(x + " " + y + " " + z); 
   }
}
  1. 0 1 -2
  2. 0 1 -3
  3. 2 1 -2
  4. 2 1 -3
  5. None of the above.
  6. The code doesn't compile.




Answer



D.

Note

After sorting, hex contains [10, 4B, 8, FF].

Remember that numbers sort before letters and strings sort alphabetically.

This makes 10 come before 8.

A binary search finds 8 at index 2 and 4B at index 1.

It cannot find 4F but notices it should be at index 2.

The rule when an item isn't found is to negate that index and subtract 1. -2-1 is -3.

public class Main{
   public static void main(String[] argv){
         List<String> hex = Arrays.asList("10", "8", "4B", "FF"); 
         Collections.sort(hex); /*from  www .  j a  v a  2 s  .  co  m*/
         
         int x = Collections.binarySearch(hex, "8"); 
         int y = Collections.binarySearch(hex, "4B"); 
         int z = Collections.binarySearch(hex, "4F"); 
         System.out.println(x + " " + y + " " + z); 
   }
}

The code above generates the following result.