首先介绍一下它们的区别,++i 使用前置增量运算符,而 i++ 使用后置增量运算符。虽然它们都增加变量 i,但是前置增量运算符在增量运算之前返回 i 的值,而后置增量运算符在增量运算之后返回值 i。一个简单的测试程序展示了这种区别:
public class Test { public static void main(String[] args) { int PRe = 1; int post = 1; System.out.println("++pre = " + (++pre)); System.out.println("post++ = " + (post++)); } }
Method int preIncrement() 0 iconst_0 //push 0 onto the stack 1 istore_0 //pop 0 from the stack and store it at lvar[0], i.e. lvar[0]=0 2 iinc 0 1 //lvar[0] = lvar[0]+1 which means that now lvar[0]=1 5 iload_0 //push lvar[0] onto the stack, i.e. push 1 6 istore_1 //pop the stack (value at top is 1) and store at it lvar[1], i.e. lvar[1]=1 7 iload_1 //push lvar[1] onto the stack, i.e. push 1 8 ireturn //pop the stack (value at top is 1) to the invoking method i.e. return 1
Method int postIncrement() 0 iconst_0 //push 0 onto the stack 1 istore_0 //pop 0 from the stack and store it at lvar[0], i.e. lvar[0]=0 2 iload_0 //push lvar[0] onto the stack, i.e. push 0 3 iinc 0 1 //lvar[0] = lvar[0]+1 which means that now lvar[0]=1 6 istore_1 //pop the stack (value at top is 0) and store at it lvar[1], i.e. lvar[1]=0 7 iload_1 //push lvar[1] onto the stack, i.e. push 0 8 ireturn //pop the stack (value at top is 0) to the invoking method i.e. return 0