preincrement / postincrement in java

后端 未结 5 552
粉色の甜心
粉色の甜心 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:02

    As the name indicates, a post increment increments the value of the variable AFTER the variable has been processed (read) while the pre incrment increments the value BEFORE.

    For i, that means that first i is incremented by 1, but read as 1, then incremented by 1 again (already being 2 now from the first increment), thus incremented to 3, but read as 2. This results in 1+2 = 3 and the value of i will be 3 as well...

提交回复
热议问题