ProgrammingVery hardProduct company OA

What is printed?

What is printed?
static int f() {
    int x = 1;
    try {
        return x;
    } finally {
        x = 2;
    }
}
public static void main(String[] a) { System.out.print(f()); }
  1. A. 1
  2. B. 2
  3. C. Compilation error
  4. D. 0

Correct answer: A. 1

For a primitive, the try's return value (1) is copied before finally executes. finally mutating x afterward does not change the already-captured return value, so 1 is printed, not 2.

More OOP with C++ and Java questions

Exams that ask this topic