Question

the output is coming as Test Passed!!! how the builder return when it is set to null at finally block

    public class Test {
    public static void main(String args[])
    {
        System.out.println(new Test().print());
    }
    protected StringBuilder print() {
        StringBuilder builder = new StringBuilder();
        try {
            builder.append("Test ");
            return builder.append("Passed!!!");
        } finally {
            builder = null; 
        }
    }
}
Was it helpful?

Solution

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!

OTHER TIPS

finally happens after everything else. This means builder will be set to null after the return (but of course, before the caller gets the result.

Note that nulling builder doesn't make much sense in this case since the builder variable is about to fall out of scope and will be cleaned up by garbage collection at some point anyway.

Basically you returned the StringBuilder contents and THEN set it to null.

finally is executed after try block either the execption is generated or not.Here is the link for your reference from Java documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top