int x = 3;
System.out.println(x++ + ++x + x++); // 13
Why is the result 13?
My logic:
++xin the center gives 44 + 4 + 4 = 12so the result must be 12.
int x = 3;
System.out.println(x++ + ++x + x++); // 13
Why is the result 13?
My logic:
++x in the center gives 44 + 4 + 4 = 12 so the result must be 12. Let's take it step-by-step. First it is important to note that expressions are evaluated from left to right, so there is no undefined behaviour.
int x = 3;
int res = x++ + ++x + x++
// res = (x++) + (++x) + (x++) with x = 3
// res = 3 + (++x) + (x++) with x = 4
// res = 3 + 5 + (x++) with x = 5
// res = 3 + 5 + 5 with x = 6
// res = 13
The key part here is that:
x++ returns the previous x value and increments x afterwards. JLS section 15.14.2 about the "Postfix Increment Operator ++" says:
The value of the postfix increment expression is the value of the variable before the new value is stored.
++x returns the next x incremented value. JLS section 15.15.1 about the "Prefix Increment Operator ++" says:
The value of the prefix increment expression is the value of the variable after the new value is stored.
System.out.println(x++ + ++x + x++); // 13
3 5 5
System.out.println(x++ + ++x + x++); // 13
x++ - executes then increments, so 3
++x - above 3 incremented to 4, ++x increments first then executes, so 4+1=5
x++ - executes first increment later, so x=5 is used, but after this execution x becomes 6
x++ is an expression evaluating to the value before the increment. When you see x++ you can think of it as
int result = x;
x = x + 1;
// do something with result.
++x can be thought of as
x = x + 1;
int result = x;
// do something with result.
The expression in the question is evaluated from left to right. You can think of it as
int x = 3
int result1 = x; // 3
x = x + 1;
x = x + 1;
int result2 = x; // 5
int result3 = x; // 5
x = x + 1;
System.out.println(result1 + result2 + result3);