为了账号安全,请及时绑定邮箱和手机立即绑定

java,麻烦深入讲解为什么结果是1?而不是2。

java,麻烦深入讲解为什么结果是1?而不是2。

慕妹3242003 2019-03-21 18:15:35
public class Test  { public static void main(String[] args)  { System.out.println(new Test().test()); }static int test()  {     int x = 1;     try      {         return x;     }     finally      {         ++x;     } } }
查看完整描述

2 回答

?
繁星coding

TA贡献1797条经验 获得超4个赞

写了个简单的类

static int test()

{

int x=5;
try

{

return x;

}

finally

{

x=10;
}

}

编译后的字节码为
这里说一下,对于try catch finally的编译,编译器会把finally里的代码附在每一个分支的后面

static int test();
0 iconst_5

1 istore_0 [x] //存在局部变量表0位置
2 iload_0 [x] //读取0位置到操作数栈

//下边是finally代码块,附在成功分支后面

  istore_2      //另存在2位置
  bipush 10     //10放入操作数栈
  istore_0 [x]  //存在0位置,所以,这时候0位置的变量为10
 iload_2       //读取2号位置,这时是5
  ireturn       //返回5

//下面是异常分子处理
9 astore_1
10 bipush 10
12 istore_0 [x]
13 aload_1
14 athrow


查看完整回答
反对 回复 2019-04-26
?
守着一只汪

TA贡献1872条经验 获得超3个赞

因为在运行到return时,该返回值/地址就已经被记录

所以finally里的改变不会起作用

但假如返回值为引用类型,finally块是可以改变其内容的

如下例子~ 想想会返回什么

public class Test

{

public static void main(String[] args)

{

System.out.println(new Test().test().toString());

}static StringBuffer test()   
{  
    StringBuffer x = new StringBuffer("hi");  
    try   
    {  
        return x;  
    }  
    finally   
    {  
        x.append("hello");  
    }  
}  

}


查看完整回答
反对 回复 2019-04-26
  • 2 回答
  • 0 关注
  • 608 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号