How do the post increment (i++) and pre increment (++i) operators work in Java?

后端 未结 14 2486
暖寄归人
暖寄归人 2020-11-21 04:45

Can you explain to me the output of this Java code?

int a=5,i;

i=++a + ++a + a++;
i=a++ + ++a + ++a;
a=++a + ++a + a++;

System.out.println(a);
System.out.p         


        
14条回答
  •  执笔经年
    2020-11-21 05:05

    when a is 5, then a++ gives a 5 to the expression and increments a afterwards, while ++a increments a before passing the number to the expression (which gives a 6 to the expression in this case).

    So you calculate

    i = 6 + 7 + 7
    i = 5 + 7 + 8
    

提交回复
热议问题