Java OCA OCP Practice Question 2797

Question

Given:

public class Main {
   String a = "12b";

   public static void main(String[] args) {
      System.out.println(new Main().print(args[0]));
   }/*from  w ww  .j  av a 2 s  .c om*/

   int print(String a) {
      if (a == null)
         throw new IllegalArgumentException();
      return Integer.parseInt(a);
   }
}

And, if the code compiles, the invocation:.

java Main 

What is the result?

  • A. 12
  • B. 12b
  • C. Compilation fails.
  • D. A NullPointerException is thrown.
  • E. A NumberFormatException is thrown.
  • F. An IllegalArgumentException is thrown.
  • G. An ArrayIndexOutOfBoundsException is thrown.


G is correct.

Note

Working backwards, if somehow we passed parseInt() the String "12b", it would throw a NumberFormatException.

If somehow we passed a null to print(), we would get an IllegalArgumentException.

But before any of that can happen, we attempt to access args[0], which throws an ArrayIndexOutOfBoundsException.




PreviousNext

Related