直接上代码:
public class Test {
public static void main(String[] args) {
System.out.println(Test.test());
}
public static String test() {
String str = "hello";
try {
str = "try";
System.out.println("first");
return str;
}catch(Exception e){
str = "catch";
return str;
}finally {
str = "finally";
System.out.println("second");
}
}
}
刚看到题目,觉得毫无疑问是”finally”,然而并不是。。。
难道finally没有执行?
于是加上调试语句,如上,
输出顺序为first, second, try,没问题,那么问题出在哪?
后来,写了如下代码:
public static String test() {
String str = "hello";
String p1 = null;
p1 = str;
if(p1 == str) {
System.out.println("equals in out");
}
try {
str = "try";
if(p1 == str) {
System.out.println("equals in try");
}
return str;
}catch(Exception e){
str = "catch";
if(p1 == str) {
System.out.println("equals in catch");
}
return str;
}finally {
str = "finally";
if(p1 == str) {
System.out.println("equals in finally");
}
}
}
只输出了”equals in out”, 也就是try, catch, finally三个代码块里的str都不是原来的str。
又写了以下代码:
String str = "eee";
String p = str;
{
if(p == str) {
System.out.println("equals1");
}
str = "aaa";
if(p == str) {
System.out.println("equals2");
}
}
只输出了”equals1”,可以看出,{ }代码块中,如果对外部定义的变量重新赋值,系统会用一个新的内存块来放这个新值。
回到一开始的题目,str = “finally” 这句代码,系统为finally代码块里的str分配了一个新的内存块,所以并不影响原来的str = “try”,所以输出还是”try”。