ProgrammingVery hardIBM · Deloitte pattern

What is printed?

What is printed?
public class Main {
    public static void main(String[] args) {
        int result = compute();
        System.out.println(result);
    }
    static int compute() {
        int x = 5;
        try {
            x = x / 0;
            return x;
        } catch (ArithmeticException e) {
            return -1;
        } finally {
            x = 100;
            System.out.print("x-in-finally=" + x + " ");
        }
    }
}
  1. A. x-in-finally=100 -1
  2. B. x-in-finally=100 100
  3. C. ArithmeticException propagates uncaught
  4. D. x-in-finally=5 -1

Correct answer: A. x-in-finally=100 -1

x / 0 for ints throws ArithmeticException, caught by the catch block, which computes a return value of -1 (saved before finally runs). finally then sets x = 100 and prints it, but that assignment doesn't change the already-decided return value, so compute() still returns -1.

More OOP with C++ and Java questions

Exams that ask this topic