JavaAdvanced#puzzle#exceptions

What does this code output and why? try { return 1; } finally { return 2; }

The finally block's return statement overrides the try block's return, so the method returns 2. This is a well-known gotcha — avoid returning from finally blocks in real code.

Example
int test() {
  try { return 1; } finally { return 2; }
}
System.out.println(test()); // Output: 2

Related Questions

1
JavaAdvanced#puzzle#collections

What is the output? List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); for (Integer i : list) { if (i == 1) list.remove(i); }

Open
2
JavaIntermediate#puzzle#oop

What is the output of this code involving static and instance initialization order? class A { static { System.out.println("static A"); } { System.out.println("instance A"); } A() { System.out.println("constructor A"); } } new A(); new A();

Open
3
JavaIntermediate#puzzle#fundamentals

What does this print? Integer a = 127; Integer b = 127; Integer c = 128; Integer d = 128; System.out.println(a == b); System.out.println(c == d);

Open