First of all, let's understand how Java handles method calls. Each thread has a separate stack memory. When we call a method, Java internally inserts the record on top of the stack. The record contains some details, such as parameters and an object, etc.
There is one interesting field here: the return value. When a return statement is encountered, the field is updated. Now follow the code.
In the try block, the return value field is set to the return value from the try block. Now, according to the execution sequence, the finally block is executed. Now the finally block changes the reference to the string s . It did not change the return value field that was previously set by the try block. Finally, the method call is completed, and Java internally issues a record and returns a return value field. Therefore, it returns the return value from the try block.
If the finally block returns the string after modification, the return value field will be updated again, and the updated string will be returned.
source share