i++ ,++i,i=i++的问题
int i=0; i=i++; 结果i是多少? 这是一个经常被提及的问题,答案一直五花八门。 具体测试一下以说明问题: 代码1:
结果i依然是0.分析其反编译后的代码:
值得注意到是i被修改了两次,第一次是i++;i变为1,最后一次是i=0;所以结果i是0 代码2:
这个结果肯定都知道,i是1,j是0.同样看反编译之后的代码:
很明显可以看出,java是先把i的值取出来放到栈顶,我们可以认为是引入了第三个变量int k=i;然后i++,这时候i为1了,然后让j=k;也就是0.结论,i的++运算是在对j这个变量的赋值之前完成的。 代码3:
结果大家也都知道,i=1,j=1 看操作过程:
对比代码2和代码3,关键的差别就是iload_1 个iinc这两条指令的位置变了。 最后把iinc指令介绍一下: iinc Operation Forms Operand Stack Description The iinc opcode can be used in conjunction with the wide instruction to access a local variable using a two-byte unsigned index and to increment it by a two-byte immediate value. Notes Increment local variable by constant 给局部变量加上一个常量的值Format
iinc = 132 (0x84)No change 操作数栈无变化 The index is an unsigned byte that must be an index into the local variable array of the current frame(§3.6). The const is an immediate signed byte. The local variable at index must contain an int . The value const is first sign-extended to an int , and then the local variable at index is incremented by that amount. 原文地址http://piaoboqiu.blog.163.com/blog/static/123127827200910192122472/ |