Question discussion

What is the output of the following Java program?public class Main { static int f() { int x = 1; try { return x; } finally { x = 2; } } pub…

1103Medium DSSSB TGT Computer Science 0 replies

What is the output of the following Java program?

public class Main {
    static int f() {
        int x = 1;
        try { return x; }
        finally { x = 2; }
    }
    public static void main(String[] args) {
        System.out.print(f());
    }
}
  • A1
  • B2
  • C12
  • DCompilation error
Correct answer: A

Explanation

The return value (1) is evaluated and saved before finally runs; changing the local x afterwards does not change it.

Discussion 0

Nobody has replied yet. Start the discussion!