Assigning null to variable in finally block [duplicate]

ぐ巨炮叔叔 提交于 2019-12-20 07:52:45

问题


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

回答1:


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;



回答2:


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



来源:https://stackoverflow.com/questions/22857120/assigning-null-to-variable-in-finally-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!