Java OCA OCP Practice Question 1424

Question

What is the output of the following when run as java Main seed flower plant?

package mypkg; //from ww  w.  j a  va2 s .com

import java.util.*; 

public class Main { 

   public static void main(String[] args) { 
      Arrays.sort(args); 
      int result = Arrays.binarySearch(args, args[0]); 
      System.out.println(result); 
  } 
} 
  • A. 0
  • B. 1
  • C. 2
  • D. The code does not compile.
  • E. The code compiles but throws an exception at runtime.
  • F. The output is not guaranteed.


A.

Note

This class is called with three command-line arguments.

First the array is sorted, which meets the pre-condition for binary search.

At this point, the array contains [flower, plant, seed].

The key is to notice the value of args[0] is now flower rather than seed.

Calling binary search to find the position of flower returns 0, which is the index matching that value.

The answer is Option A.




PreviousNext

Related