代码示例:
public class Demo02 {
public static void main(String[] args) {
Too too=new Too();
StringBuilder t1=test(too);
System.out.println("return语句返回的:"+t1+"\t返回值的hashCode:"+t1.hashCode());
System.out.println("finaly里面修改的:"+too.num+"\tfinaly的hashCode:"+too.num.hashCode());
}
public static StringBuilder test(Too too) {
try {
too.num=new StringBuilder("try");
System.out.println("try字符串的hashcode:"+("try").hashCode());
System.out.println("StringBuilder里的try的hashCode:"+too.num.hashCode());//--语句1
return too.num; //语句2
} finally {
too.num=new StringBuilder("finaly");//语句3
System.out.println("finaly的hashCode:"+too.num.hashCode());//语句4
}
}
}
class Too{
StringBuilder num=new StringBuilder("你好");
}
执行输出结果:
try字符串的hashcode:115131
StringBuilder里的try的hashCode:460141958
finaly的hashCode:1163157884
return语句返回的:try 返回值的hashCode:460141958
finaly里面修改的:finaly finaly的hashCode:1163157884
原因解析:
如果try语句里有return,那么代码的行为如下:
1)如果有返回值,就把返回值保存到局部变量中
2)执行jsr指令跳到finally语句里执行
3)执行完finally语句后,返回之前保存在局部变量表里的值。