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

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

    ++a increments a before it is evaluated. a++ evaluates a and then increments it.

    Related to your expression given:

    i = ((++a) + (++a) + (a++)) == ((6) + (7) + (7)); // a is 8 at the end
    i = ((a++) + (++a) + (++a)) == ((5) + (7) + (8)); // a is 8 at the end
    

    The parenteses I used above are implicitly used by Java. If you look at the terms this way you can easily see, that they are both the same as they are commutative.

提交回复
热议问题