Reputation: 91
Why is the result 8 and not 9?
By my logic:
++x
gives 4x = 8
x
should be increased due to x++
, so it should be 9.What's wrong with my logic?:
int x = 3;
x = x++ + ++x;
System.out.println(x); // Result: 8
Upvotes: 5
Views: 391
Reputation: 953
++x is called preincrement and x++ is called postincrement. x++ gives the previous value and ++x gives the new value.
Upvotes: 1
Reputation: 393771
You should note that the expression is evaluated from the left to the right :
First x++
increments x but returns the previous value of 3.
Then ++x
increments x and returns the new value of 5 (after two increments).
x = x++ + ++x;
3 + 5 = 8
However, even if you changed the expression to
x = ++x + x++;
you would still get 8
x = ++x + x++
4 + 4 = 8
This time, the second increment of x (x++
) is overwritten once the result of the addition is assigned to x.
Upvotes: 21