I just wanted to create a little Java-Puzzle, but I puzzled myself. One part of the puzzle is:
What does the following piece of code do:
public class test {
public static void main(String[] args) {
int i = 1;
i += ++i + i++ + ++i;
System.out.println("i = " + i);
}
}
It outputs 9
.
My (at least partly) wrong explanation:
I'm not quite sure, but I think the term after i +=
gets evaluated like this:
So
int i = 1;
i += ++i + i++ + ++i;
is the same as
int i = 1;
i += ((++i) + (i++)) + (++i);
This gets evaluated from left to right (See Pre and postincrement java evaluation).
The first ++i
increments i
to 2
and returns 2
. So you have:
i = 2;
i += (2 + (i++)) + (++i);
The i++
returns 2
, as it is the new value of i
, and increments i
to 3
:
i = 3;
i += (2 + 2) + ++i;
The second ++i
increments i
to 4
and returns 4
:
i = 4;
i += (2 + 2) + 4;
So you end up with 12
, not 9
.
Where is the error in my explanation? What would be a correct explanation?
i += ++i + i++ + ++i;
is the same as i = i + ++i + i++ + ++i;
The right-hand side is calculated from left-to-right, yielding i = 1 + 2 + 2 + 4;
(which yields i = 9
).
The output is 9 (try it)
int i = 1;
i += ++i + i++ + ++i;
becomes
i = 1 + 2 + 2 + 4
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