public void testFinally(){
System.out.println(setOne().toString());
}
protected StringBuilder setOne(){
StringBuilder builder=new StringBuilder();
try{
builder.append("Cool");
return builder.append("Return");
}finally{
builder=null; /* ;) */
}
}
why output is CoolReturn, not null?
Regards,
Mahendra Athneria
The expression is evaluated to a value in the return statement, and that's the value which will be returned. The finally block is executed after the expression evaluation part of the return statement.
Of course, the finally block could modify the contents of the object referred to by the return value - for example:
finally {
builder.append(" I get the last laugh!");
}
in which case the console output would be "CoolReturn I get the last laugh!" - but it can't change the value which is actually returned.
apparently it looks it should be null but with the concept of pass by reference in java here is how it goes :
1> return builder.append("Return")
... line gets executed and the copy of builder reference is returned to the testFinally() method by pass by reference
2> While executing builder=null
in finally block the builder reference gets dereferenced but the actual object which is in the heap which was referenced by the builder reference earlier still present in the heap and the returned copy of the builder reference (which is also a reference pointing to the same object) still exists and that's holding the value "CoolReturn" , thats why its printing the returned value .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With