javapost-incrementpre-increment

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


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.println(i);

The output is 20 in both cases


Solution

  • 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.