Because the result of the return
is a copy of the reference of the builder
in that moment.
builder = null;
in finally
code doesn't alter this reference, instead just replaces the current value of the builder
variable inside print
method.
Still, note that if you alter the state of the object reference that is returned, this will affect the result of the returned value. For example:
protected StringBuilder print() {
StringBuilder builder = new StringBuilder();
try {
builder.append("Test ");
return builder.append("Passed!!!");
} finally {
builder.append(" but modified!");
//builder = null;
}
}
It will print:
Test Passed!!! but modified!