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

后端 未结 14 2489
暖寄归人
暖寄归人 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:12

    Does this help?

    a = 5;
    i=++a + ++a + a++; =>
    i=6 + 7 + 7; (a=8)
    
    a = 5;
    i=a++ + ++a + ++a; =>
    i=5 + 7 + 8; (a=8)
    

    The main point is that ++a increments the value and immediately returns it.

    a++ also increments the value (in the background) but returns unchanged value of the variable - what looks like it is executed later.

提交回复
热议问题