ProgrammingVery hardProduct company interview · GATE level

What is printed?

What is printed?
// static methods of the main class:
static int f() {
    int x = 1;
    try {
        x = 2;
        throw new IllegalStateException();
    } catch (IllegalStateException e) {
        x = 3;
        return x;
    } finally {
        x = 4;
        System.out.print(x + " ");
    }
}
static int g() {
    try {
        throw new RuntimeException("g");
    } finally {
        return 5;
    }
}
// in main:
System.out.print(f() + " ");
System.out.print(g());
  1. A. 3 4 5
  2. B. 4 4 5
  3. C. 4 3 5
  4. D. 4 3 followed by RuntimeException: g

Correct answer: C. 4 3 5

In f, the catch block evaluates return x when x is 3, and that value is saved before finally runs. finally sets x = 4 and prints '4 ', but changing the local variable does not change the saved return value, so f returns 3 and main prints '3 '. In g, the finally block's return completes the method normally and discards the pending RuntimeException, so g returns 5 with no exception. Output: 4 3 5.

More OOP with C++ and Java questions

Exams that ask this topic