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?