Why StringBuilder does not print what it should print in a small code
public final class Test1 {
public void test() {
System.out.println(setFin().toString());
}
protected StringBuilder setFin() {
StringBuilder builder = new StringBuilder();
try {
builder.append("John");
return builder.append("Ibrahim");
} finally {
System.out.println("In finaly"); // builder.append("-DarElBeida");
builder = null;
}
}
public static void main(String args[]){
new Test1().test();
}
}
In the last statement executed in setFin()
(in the finally
block) I have assigned null
to builder
, but my code prints "In finally"
and then "JohnIbrahim"
. Can anybody explain to me what is going on here?
When there is a return
statement inside the try
block, it will execute the finally
block before actually returning.
And the method doesn't return null
because the return
statement holds a reference to the actual StringBuilder object, not to the variable builder
.
Setting builder == null
doesn't delete the StringBuilder itself, it just drops builder
's reference to it.
This behavior can be confusing. To make things clear it could be helpful to return from outside the try/catch/finally block:
StringBuilder builder = new StringBuilder();
try {
builder.append("John");
builder.append("Ibrahim");
} finally {
System.out.println("In finaly"); // builder.append("-DarElBeida");
builder = null;
}
return builder;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With