Here is an example that outputs 6:
public static void main(String[] args) {
int i = 1;
m(++i);
}
static void m(int i) {
i = ++i + i++;
System.out.println(i);
}
We get 6 because in the m(int i) method at first 3 and 3 are summarized, then i becomes 4 (due to the i++), but after that i from the left part takes the summarized 6 value.
But if the method is changed to the following, we get 7:
static void m(int i) {
i = ++i + ++i;
System.out.println(i);
}
But I expected to see 7 in both cases (I’ve been guided by the fact that unary operations, in this case incrementing, have a higher priority than binary operations). Could someone please provide an explanation (or a reference to an explanation) of the ignored i++ in the first example?
++iincrementsiand returns the new value ofi.i++incrementsiand returns the old value ofi.Expressions are evaluated from left to right, taking operator precedence into account.
So in
++i + i++, when you start withi == 2, you get:++iwhich incrementsito3and returns3; theni++which incrementsito4and returns3. Then finally you havei = 3 + 3soibecomes6.Note that these are funny tricks that are not really relevant to real-world programming.