OCA Java SE 8 Mock Exam - OCA Mock Question 25








Question

What is the output of the following code?

public class Main {
  void foo() {
    try {
      String s = null;
      System.out.println("1");
      try {
        System.out.println(s.length());
      } catch (NullPointerException e) {
        System.out.println("inner");
      }
      System.out.println("2");
    } catch (NullPointerException e) {
      System.out.println("outer");
    }
  }

  public static void main(String args[]) {
    Main obj = new Main();
    obj.foo();
  }
}

             a   1 
                 inner 
                 2 
                outer 

             b   1 
                outer 

             c   1 
                 inner 

             d   1 
                 inner 
                 2 





Answer



D

Note

Since the variable s hasn't been initialized, an attempt to access its method length() will throw a NullPointerException.

The inner try-catch block handles this exception and prints inner.

The control then moves on to complete the remaining code in the outer try-catch block.