Java Tricky Question: Finally Block Execution and Return Value

#ThinkingInJava — Post No. 5 💡 Tricky Java Question What will be the output? class Test { public static int m1() { int i = 10; try { return i; } finally { i = 20; System.out.println("finally block executed"); } } public static void main(String[] args) { System.out.println(m1()); } } ✅ Output finally block executed 10 🤔 Why not 20? When return i executes, Java first saves the return value internally. temp = i // temp = 10 Then the "finally" block runs, changing i to 20. But the method returns the saved value (10). 🎯 Key Concept 👉 The return value is evaluated before the `finally'. #Java #TestAutomationSpecialist #AutomationMeetsFuture

To view or add a comment, sign in

Explore content categories