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

后端 未结 14 2483
暖寄归人
暖寄归人 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题