Why the modification done to output in finally gets lost?
Excellent question. Answer : Because output which is of type
String is immutable.
See the code below. Just replaced String with Stringbuffer which is mutable.
Here you will get the following output
b
b
bab
bab
In both code snippets return happens first; then the finally executes.
In the first code snippet the instance of the String referred by variable output changed with each '+' operation.
In the second code snippet the instance of the String referred by variable output didn't change with append.
In the first code snippet, the object referenced by output contained ba and that refrence is returned. Then when finally executed a new String instance is created (because String is immutable) and value of Output is changed to refer to new instance. Hence the print statement from finally had the most recent instance which contained 'bab' and the print statement from main had the second most recent instance which contained 'ba'.
Please let me know if this explanation make sense.