Java OCA OCP Practice Question 1381

Question

What is the output of the following application?

package mypkg; /*from   w w  w  . jav  a2s  .  c  om*/
public class Main { 
   public static void m(int... p) throws ClassCastException { 
      try { 
         System.out.print("1"+p[2]);  // p1 
      } catch (RuntimeException e) { 
         System.out.print("2"); 
      } catch (Exception e) { 
         System.out.print("3"); 
      } finally { 
         System.out.print("4"); 
      } 
   } 
   public static void main(String... music) { 
      new Main().m(0,0);  // p2 
      System.out.print("5"); 
   } 
} 
  • A. 145
  • B. 1045
  • C. 24, followed by a stack trace
  • D. 245
  • E. The code does not compile because of line p1.
  • F. The code does not compile because of line p2.


D.

Note

The code compiles without issue, so Options E and F are incorrect.

Line p2 accesses a static method using an instance reference, which is discouraged but permitted in Java.

First, A varargs int array of [0,0] is passed to the m() method.

The try block throws ArrayIndexOutOfBoundsException, since the third element is requested and the size of the array is two.

The print() statement in the try block is not executed.

Next, since ArrayIndexOutOfBoundsException is a subclass of RuntimeException, the RuntimeException catch block is executed and 2 is printed.

The rest of the catch blocks are skipped, since the first one was selected.

The finally block then executes and prints 4.

Lastly, control is returned to the main() method without an exception being thrown, and 5 is printed.

Since 245 is printed, Option D is the correct answer.




PreviousNext

Related