ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
public int test() {
    try {
        return 1;
    } finally {
        System.out.println("finally");
    }
}
// caller: System.out.println(test());
  1. A. 1\nfinally
  2. B. Compilation error: cannot return from try with a finally present
  3. C. finally\nfinally
  4. D. finally\n1

Correct answer: D. finally\n1

The finally block always executes before the method actually returns to its caller, even though the return value (1) was already computed and 'queued' by the try block. So "finally" prints first, then the caller's println outputs 1.

More OOP with C++ and Java questions

Exams that ask this topic