ProgrammingHardTCS NQT · Infosys · Accenture

What does this Java program print? static int f() { int x = 1; try { return x; } finally { x = 3; } } static int g() { try { throw new RuntimeException(); } finally { return 5; } } // in main: System.out.println(f() + g());

  1. A. 8
  2. B. 4
  3. C. 6
  4. D. RuntimeException is thrown

Correct answer: C. 6

In f the return value 1 is saved before the finally block runs, so changing x to 3 has no effect. In g, the return inside finally overrides and discards the exception, so g returns 5. The total is 1 + 5 = 6.

More OOP with C++ and Java questions

Exams that ask this topic