object reference set to null in finally block

荒凉一梦 提交于 2019-12-06 18:47:21

问题


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


回答1:


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.




回答2:


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 .




回答3:


The finally block is used for "cleanup", after the execution of the try block. As you returned the reference already, you can not change it in this way.



来源:https://stackoverflow.com/questions/4625650/object-reference-set-to-null-in-finally-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!