Java OCA OCP Practice Question 2678

Question

Given:

import java.util.Arrays;
import java.util.Comparator;

public class Main {
   public static void main(String[] args) {
      String[] towns = { "aspen", "vail", "t-ride", "dillon" };
      MySort ms = new MySort();
      Arrays.sort(towns, ms);//from  w ww  .ja  v  a  2  s. com
      System.out.println(Arrays.binarySearch(towns, "dillon"));
   }

   static class MySort implements Comparator<String> {
      public int compare(String a, String b) {
         return b.compareTo(a);
      }
   }
}

What is the most likely result?

  • A. -1
  • B. 1
  • C. 2
  • D. 3
  • E. Compilation fails.
  • F. An exception is thrown at runtime.


A is correct.

Note

The binarySearch() method gives meaningful results only if it uses the same Comparator as the one used to sort the array.

The static inner class is legal, and on the real exam expect to find inner classes sprinkled throughout questions that are focused on other objectives.




PreviousNext

Related