OCA Java SE 8 Mock Exam - OCA Mock Question 28








Question

What is the output of the following code?

int a = 10; 
String name = null; 
try { 
    a = name.length(); 
    a++; 
} 
catch (RuntimeException e){ 
    ++a; 
} 
System.out.println(a); 
  1. 5
  2. 6
  3. 10
  4. 11
  5. 12
  6. Runtime exception




Answer



D

Note

Because the variable name isn't assigned a value, the following line of code will throw NullPointerException:

name.length(); 

Then control is transferred to the exception handler, which increments the value of the variable a to 11.

public class Main {
  public static void main(String args[]) {
    int a = 10;/*www  .ja  v a 2 s . c o  m*/
    String name = null;
    try {
      a = name.length();
      a++;
    } catch (RuntimeException e) {
      ++a;
    }
    System.out.println(a);
  }
}

The code above generates the following result.