Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object reference set to null in finally block

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

like image 945
Mahendra Athneria Avatar asked Jan 07 '11 12:01

Mahendra Athneria


2 Answers

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.

like image 109
Jon Skeet Avatar answered Oct 21 '22 02:10

Jon Skeet


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 .

like image 20
Som Avatar answered Oct 21 '22 02:10

Som