Friday, January 7, 2011

set object reference 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; /* ;) */
}
}

So what would be the output? Mostly said it would be null as I had guess it very first time.

But the output is - CoolReturn.

Here is the description-

In the setOne method its create a new Object of StringBuilder i.e. builder.

Now in next step we append “Cool” string

Now in next step we append "Return" String

Now next is the return step. Here return statement get the builder reference that is pointing to the

“CoolReturn” string and put it into the stack.

Now in finally block builder point to the null reference.

Now control goes back to the return statement, here return pull the builder reference from stack which is pointing to the “CoolReturn” string and return back the "CoolReturn" string.

So the output is “CoolReturn”.