我怀疑为什么在下面的代码中输出分别为2和1? 这真的好吗? 对于我的看法,方法' m'应该收到值1,因为它在变量' i'上使用了后缀运算符。而不是前缀运算符。
public class PostfixDoubt {
public static void main(String[] args) {
int i = 1;
// why does m receive 2 as argument and not 1?
i = i++ + m(i);
System.out.println(i);
}
public static int m(int i) {
System.out.println(i);
return 0;
}
}
Bellow是用javap反编译的字节码:
public class PostfixDoubt {
public PostfixDoubt();
Code:
0: aload_0
1: invokespecial #8 // Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_1
1: istore_1
2: iload_1
3: iinc 1, 1
6: iload_1
7: invokestatic #16 // Method m:(I)I
10: iadd
11: istore_1
12: getstatic #20 // Field java/lang/System.out:Ljava/io/PrintStream;
15: iload_1
16: invokevirtual #26 // Method java/io/PrintStream.println:(I)V
19: return
public static int m(int);
Code:
0: getstatic #20 // Field java/lang/System.out:Ljava/io/PrintStream;
3: iload_0
4: invokevirtual #26 // Method java/io/PrintStream.println:(I)V
7: iconst_0
8: ireturn
}
答案 0 :(得分:2)
此操作
i++
递增存储在i
变量中的值并返回其先前的值。重新评估i
作为参数传递给
m(i)
使用新的递增值。
int i = 1;
i = i++ + m(i);
看起来像
1: 1 (i = 2) + m(i)
2: 1 (i = 2) + m(2)
3: 1 (i = 2) + Whatever value m(2) returns
4: whatever value is the result of that addition
5: that value is assigned to i