Today I came across a scenario wherein an assignment was done inside a finally block, a similar code snippet as below
public static void main(String[] abc) {
System.out.println("Returned \t"+ testFinally());
}
public static int testFinally() {
int aVariable =2;
try {
System.out.println("value of aVariable inside try \t"+aVariable);
return aVariable;
} finally {
aVariable = 100;
System.out.println("value of aVariable inside finally \t"+aVariable);
}
}
The output was bit strange to me
value of aVariable inside try 2
value of aVariable inside finally 100
Returned 2
Then I tried the same with StringBuffer and String
With StringBuffer
public static StringBuffer testFinallyStringBuffer() {
StringBuffer strBuffer = new StringBuffer("ABCD");
try {
System.out.println("value of strBuffer inside try \t"+strBuffer);
return strBuffer;
} finally {
strBuffer.append("EFGN");
System.out.println("value of strBuffer inside finally \t"+strBuffer);
}
}
Output
value of strBuffer inside try ABCD
value of strBuffer inside finally ABCDEFGN
Returned ABCDEFGN
Output was as expected.
With String
public static String testFinallyString() {
String str = "ABCD";
try {
System.out.println("value of str inside try \t"+str);
return str;
} finally {
str = str + "EFGN";
System.out.println("value of str inside finally \t"+str);
}
}
Output
value of str inside try ABCD
value of str inside finally ABCDEFGN
Returned ABCD
From this behavior, it seems as if variable(primitive/immutable objects/mutable objects) was passed from try block to finally block like parameters are passed to a method. Although, use of finally block is to do clean-up activities.But I want to know if my understanding is correct or there is something more to it.
Update
Though, I could not found anything satisfactory from the Question Question with which this Question has been marked DUPLICATE with. However, there are few comments claiming that the evaluation of Return statement happens only once.
Having said that, Still variables are local scope. Any change made to them should be visible on accessing these later on.
Possibly, RETURN internally creates a copy of variable being returned(right before invocation of finally and actually returning to calling method) which is why primitive variable and immutable objects behaves different from mutable objects in this case.