ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
public class Main {
    static int f() {
        int x = 10;
        try {
            return x;
        } finally {
            x = 20;
        }
    }
    public static void main(String[] a) { System.out.println(f()); }
}
  1. A. 20
  2. B. 10
  3. C. Compile-time error: x is modified after being returned
  4. D. 0

Correct answer: B. 10

return x evaluates and saves the return value (10) before finally runs. finally then reassigns the local variable x, but that happens too late to affect the value already captured for return, so the method returns 10.

More OOP with C++ and Java questions

Exams that ask this topic