Assigning null to variable in finally block [dupli

2019-03-07 03:52发布

问题:

This question already has an answer here:

  • Does a finally block always get executed in Java? 46 answers

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