Java OCA OCP Practice Question 3185

Question

Which statements are true about the following program?

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    if (args.length != 1) return;
    printIndex(args[0]);/*  ww w  . jav a 2 s. co  m*/
  }

  public static void printIndex(String key) {
    String[] strings = {"small", "smaller", "smallest", "tiny"};
    System.out.println(Arrays.binarySearch(strings , key));
  }
}

Select the two correct answers.

  • (a) The largest value ever printed by the printIndex() method is 3.
  • (b) The largest value ever printed by the printIndex() method is 4.
  • (c) The largest value ever printed by the printIndex() method is 5.
  • (d) The smallest value ever printed by the printIndex() method is 0.
  • (e) The smallest value ever printed by the printIndex() method is -4.
  • (f) The smallest value ever printed by the printIndex() method is -5.
  • (g) The smallest value ever printed by the printIndex() method is -3.


(a) and (f)

Note

The largest value a match can return is the largest index, i.e., array.length-1 (==3).

The key must be equal to the largest element in the array.

If no match is found, a negative value is returned, which is computed as follows: (insertion point + 1).

The smallest value is returned for a key that is greater than the largest element in the array.

This key must obviously be placed at the index array.length (==4), after the largest element, i.e., the insertion point is 4.

The value of the expression (insertion point + 1) is -5, which is the smallest value printed by the method.




PreviousNext

Related