public class C { public static void main(String[] arg){ int a=0; int b=0; System.out.println(a); a=a++; System.out.println(a); b=a++; System.out.println(a); System.out.println(b); } }
问题来了,这个程序运行后将打印出什么结果。答案是
0 0 1 0
那么问题又来了,为什么会出现这么诡异的答案?
我们慢慢的看
首先应该是在栈中声明了两个int对象 a、b 并初始值0
然后看a=a++;为了区分两个a 我们暂且这样写,a0=a1++;
然后这个a1把值传递给了a0,然后a1自加了一次。但是自加的值并没有传递给a0;
接着看 b=a++;
按照上面的理解先赋值然后++;这样b=0
虽然不看字节码的实际操作,但是可以这样理解,a=a++;这种操作呢,是先赋值后进行++的,和++a不同。同时int对象赋值操作是值传递而不是引用,那么赋值完毕后呢,原始对象的改写不会引用到新的对象上。所以造成了这种结果。
扫描二维码关注公众号,回复:
843222 查看本文章
下面贴出字节码文件代码(这个看不太懂,贴出供参考)
// Compiled from Test.java (version 1.6 : 50.0, super bit) public class Test { // Method descriptor #6 ()V // Stack: 1, Locals: 1 public Test(); 0 aload_0 [this] 1 invokespecial java.lang.Object() [8] 4 return Line numbers: [pc: 0, line: 1] Local variable table: [pc: 0, pc: 5] local: this index: 0 type: Test // Method descriptor #15 ([Ljava/lang/String;)V // Stack: 2, Locals: 3 public static void main(java.lang.String[] arg); 0 iconst_0 1 istore_1 [a] 2 iconst_0 3 istore_2 [b] 4 getstatic java.lang.System.out : java.io.PrintStream [16] 7 iload_1 [a] 8 invokevirtual java.io.PrintStream.println(int) : void [22] 11 iload_1 [a] 12 iinc 1 1 [a] 15 istore_1 [a] 16 getstatic java.lang.System.out : java.io.PrintStream [16] 19 iload_1 [a] 20 invokevirtual java.io.PrintStream.println(int) : void [22] 23 iload_1 [a] 24 iinc 1 1 [a] 27 istore_2 [b] 28 getstatic java.lang.System.out : java.io.PrintStream [16] 31 iload_1 [a] 32 invokevirtual java.io.PrintStream.println(int) : void [22] 35 getstatic java.lang.System.out : java.io.PrintStream [16] 38 iload_2 [b] 39 invokevirtual java.io.PrintStream.println(int) : void [22] 42 return Line numbers: [pc: 0, line: 5] [pc: 2, line: 6] [pc: 4, line: 7] [pc: 11, line: 8] [pc: 16, line: 9] [pc: 23, line: 10] [pc: 28, line: 11] [pc: 35, line: 12] [pc: 42, line: 14] Local variable table: [pc: 0, pc: 43] local: arg index: 0 type: java.lang.String[] [pc: 2, pc: 43] local: a index: 1 type: int [pc: 4, pc: 43] local: b index: 2 type: int }