Java Return Statement Behavior in Try-Finally Blocks

Simple code. Subtle behavior. Easy to misjudge. Two similar Java methods. Two completely different outputs. Case 1-> public static int tricky1() { int x = 10; try { return x; } finally { x = 50; } } Output: 10 Explanation: When return x executes, Java evaluates and stores the value (10) first. After that, the finally block runs. Even though x becomes 50 inside finally, it does not change the already prepared return value. Case 2-> public static int tricky2() { try { return 10; } finally { return 30; } } Output: 30 Explanation: If finally contains a return statement, it overrides any previous return from try or catch. This is why returning from finally is considered bad practice — it can override results and even hide exceptions. #Java #CoreJava

To view or add a comment, sign in

Explore content categories