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

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;
    }
}
}


慕妹3242003
浏览 609回答 2
2回答

繁星coding

写了个简单的类static int test() { int x=5; try { return x; } finally { x=10; } }编译后的字节码为这里说一下,对于try catch finally的编译,编译器会把finally里的代码附在每一个分支的后面static int test();0 iconst_51 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_110 bipush 1012 istore_0 [x]13 aload_114 athrow

守着一只汪

因为在运行到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");       }   }   }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java