preincrement / postincrement in java

后端 未结 5 551
粉色の甜心
粉色の甜心 2020-12-01 17:35

Can someome help me to understand why:

int i=1;
int j=1;
int k=1;
int l=1;

System.out.println(i++ + i++);  
System.out.println(++j + ++j);  
System.out.pri         


        
5条回答
  •  醉酒成梦
    2020-12-01 18:10

    i++ + i++
    

    means use i, then increment, so i is pushed to some kind of stack,

    then increased by 1,

    then the operator (+) is pushed to the stack,

    then i (now 2) is pushed to the stack.

    Since the expresseion is now over, the values and operator are popped: the 2nd i is 2, the first i is 1, 2+1=3 (i is now 3, since it was incremented after being pushed).

    The thing you are probably missing is that i isn't increased after the evaluation of the whole expression, in the case of a postincrement, and vice versa for preincrement.

提交回复
热议问题