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;
}
}
Basically, what Java does is the following:
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:
The answer is simple.
Finally
block will be executed for sure, since you are not returning any value from it, thetry
block returned value will be passed to original callerThus, you are getting "Test Passed!!!"
Changing the code to
will certainly print "null" as you expected