Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why StringBuilder does not print?

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?

like image 685
Jitendra Prajapati Avatar asked Aug 04 '13 12:08

Jitendra Prajapati


1 Answers

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;
like image 185
Dennis Traub Avatar answered Sep 22 '22 01:09

Dennis Traub