在try里面已经return x;所以a=x=1;但是finally还会执行,所以x=2但是已经没有变量来接受它了,如果你想看到它在Test里定义一个类变量,代码如下: public class Test {
/** * @param args */ static int x; public static void main(String[] args) { int a = Test.test(); int b = Test.x; System.out.println(a); System.out.println(b); }
static int test() { try { x = 1; return x; } finally { ++x;
int x = 1;
try {
return x;
}
finally
{
++x;
}
}
约等于:
static int test() {
int x = 1;
int temp = x;
++x;
return temp;
}
Code:
0: iconst_1
1: istore_0
2: iload_0
3: istore_2
4: iinc 0, 1
7: iload_2
8: ireturn
9: astore_1
10: iinc 0, 1
13: aload_1
14: athrow
上面test方法所生成的字节码,可以看到虚拟机会先把要返回的结果用一个局部变量存起来,等执行完finally后再返回这个局部变量的值,所以在finally里面对x的改变不会对返回值造成影响。
public class Test {
/**
* @param args
*/
static int x;
public static void main(String[] args) {
int a = Test.test();
int b = Test.x;
System.out.println(a);
System.out.println(b);
}
static int test() {
try {
x = 1;
return x;
}
finally
{
++x;
}
}
}
求给分。
public class Test
{ /**
* @param args
*/
public static void main(String[] args)
{
int a = Test.test();
System.out.println(a);
} static int test()
{
int x = 1;
try
{
return x;
// System.out.println("是先return了还是先finally");
}
finally
{
System.out.println("finally干活没,++x前:" + x);
++x;
System.out.println("++x后:" + x);
}
}
}
//
// 这题真坑爹,被谁翻上来了,下面是我能想到知识点:
//
// 1、++x和x++区别
//
// 2、try...finally执行
//
// 3、finally和return
//
// 4、和static{} 静态代码段区分(看的眼花,我困了估计)
//
// 5、JVM原理
你会得到另外一个答案!
为什么呢?因为finally语句是执行在return中间的,第一个try里面的return执行后并没有结束语句,之后进行了finally里面的语句,然后进行了第二次return语句,所有你就得到了另外一种答案!