What is the execution result of the following code?
publc int test(){int x;try{x = 1;return x;}catch(Exception e){x = 2;return x;}finally{x = 3;}}
I believe that a friend familiar with Java will immediately give the correct answer: 1 is returned normally, and 2 is returned if an exception occurs. When I saw this code for the first time, I had doubts about x = 3 in finally, and I was not sure whether the final returned x was changed to 3, it was not until the bytecode of this code was found in the deep understanding of Java virtual machine that it understood its operating mechanism. The following is the bytecode of the above Java code:
Public int test (); Code: Stack = 1, Locals = 5, Args_size = 1 0: iconst_1 // write 1 to the top 1 of the Stack: istore_1 // write the top value of the stack (1) to 2nd int local variables; 2: iload_1 // load 2nd int local variables to the top of the stack (start of Return Statement) 3: istore 4 // Save the stack top value to 4th int local variables. At this time x = 1 5: iconst_3 // write 3 to the stack top (Finally started) 6: istore_1 // write 3 to 2nd int local variables 7: iload 4 // laod the value of 4th int local variables to the Top 9 of the stack: ireturn // return the stack top value 10: astore_2 11: iconst_2 12: istore_1 13: iload_1 14: istore 4 16: iconst_3 17: istore_1 18: iload 4 20: ireturn 21: astore_3 22: iconst_3 23: istore_1 24: aload_3 25: athrow
From the bytecode above, the Return Statement is divided into two parts: istore 4 and iload 4 & ireturn. The finally code is inserted between store and load, the value of x is first stored in a specified position and then executed in the finally statement. In this case, the code in finally cannot affect the return value.