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

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

问题描述:

[code="java"]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;
    }
}

}[/code]

昨天没时间,今天继续补全,既然是深入,就深入点咯
记得给我加分哈~~

写了个简单的类

[code="java"]
static int test()

{

int x=5;
try

{

return x;

}

finally

{

x=10;
}

}

[/code]

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

[code="java"]
static int test();
0 iconst_5

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

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

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

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

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

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

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

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

[code="java"]
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");  
    }  
}  

}

[/code]