我理解后增量和前增量之间的区别,但我不明白这一点:
int b = 1;
b = b++;
System.out.println(b); // --> 1
为什么会打印 1? b 获取 b++ 的值(即 1)后,b 不是递增吗?
int x = 1;
b = x++;
System.out.println(b); // --> 1
System.out.println(x); // --> 2
这是我期望的行为。两边使用相同的变量(b = b++)有什么不同?
最佳答案
如果你仔细观察字节码..你可以观察到差异..稍微改变你的代码..
public static void main(String[] args) {
int b = 1;
b = b++;
System.out.println(b); // --> 1
b=1;
b=++b;
System.out.println(b); // --> 2
}
字节码:
public static void main(java.lang.String[]);
descriptor: ([Ljava/lang/String;)V
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=2, args_size=1
0: iconst_1 --> int constant 1
1: istore_1 --> store 1 in slot 1 of var table i.e, for b
2: iload_1 --> load value of b from stack --> load 1
3: iinc 1, 1 --> increment value b --> store 2 for b
6: istore_1 --> store value of b "which was loaded" --> store 1 to b.. So effectively 1
7: getstatic #22 // Field java/lang/System.out:Ljava
/io/PrintStream;
10: iload_1
11: invokevirtual #28 // Method java/io/PrintStream.print
ln:(I)V
14: iconst_1
15: istore_1 --> store 1 in slot 1 of var table i.e, for b
16: iinc 1, 1 --> increment --> b=2
19: iload_1 --> load 2
20: istore_1 --> store 2.. So, effectively 2
21: getstatic #22 // Field java/lang/System.out:Ljava
/io/PrintStream;
24: iload_1
25: invokevirtual #28 // Method java/io/PrintStream.print
ln:(I)V
28: return
LineNumberTable:
line 13: 0
line 14: 2
line 15: 7
line 16: 14
line 17: 16
line 18: 21
line 25: 28
LocalVariableTable:
Start Length Slot Name Signature
0 29 0 args [Ljava/lang/String;
2 27 1 b I
关于java - 递增变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27147832/