以下代码的输出是“Test Passed”;有人可以向我解释原因吗?
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;
}
}
答案 0 :(得分:7)
基本上,Java的作用如下:
StringBuilder valueToReturn = builder.append("Passed!!!");
executeFinallyBlock();
return valueToReturn;
无论你在finally块中做什么,Java都会保留对要返回的值的引用,并返回该引用。所以它变成了:
StringBuilder valueToReturn = builder.append("Passed!!!");
builder = null;
return valueToReturn;
答案 1 :(得分:0)
答案很简单。
Finally
块将被执行,因为您没有从中返回任何值,try
块返回的值将被传递给原始调用者
try {
builder.append("Test ");
return builder.append("Passed!!!");
} finally {
builder = null;
}
因此,您正在接受测试通过!!!"
将代码更改为
StringBuilder builder = new StringBuilder();
try {
builder.append("Test ");
return builder.append("Passed!!!");
} finally {
return null;
}
肯定会打印" null"正如你所料