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?
++i increments i and returns the new value of i.
i++ increments i and returns the old value of i.
Expressions are evaluated from left to right, taking operator precedence into account.
So in ++i + i++, when you start with i == 2, you get: ++i which increments i to 3 and returns 3; then i++ which increments i to 4 and returns 3. Then finally you have i = 3 + 3 so i becomes 6.
Note that these are funny tricks that are not really relevant to real-world programming.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With