Assigning null to variable in finally block [dupli

2019-03-07 04:04发布

This question already has an answer here:

The output of the following piece of code is "Test Passed"; can someone explain to me why ?

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; 
    }
}

2条回答
做自己的国王
2楼-- · 2019-03-07 04:13

Basically, what Java does is the following:

StringBuilder valueToReturn = builder.append("Passed!!!");
executeFinallyBlock();
return valueToReturn;

Whatever you're doing inside the finally block, Java has kept a reference to the value to return, and returns that reference. So it becomes:

StringBuilder valueToReturn = builder.append("Passed!!!");
builder = null;
return valueToReturn;
查看更多
劳资没心,怎么记你
3楼-- · 2019-03-07 04:29

The answer is simple.

Finally block will be executed for sure, since you are not returning any value from it, the try block returned value will be passed to original caller

try {
    builder.append("Test ");
    return builder.append("Passed!!!");
} finally {
    builder = null; 
}

Thus, you are getting "Test Passed!!!"

Changing the code to

StringBuilder builder = new StringBuilder();
try {
    builder.append("Test ");
    return builder.append("Passed!!!");
} finally {
    return null;
}

will certainly print "null" as you expected

查看更多
登录 后发表回答