Search code examples
javafinallytry-finally

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


Solution

  • 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.