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