0
x=10;
y = --x + x++;
System.out.println(y);
// prints 18    

As per the link https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html, postfix increment(x++) has higher precedence than prefix increment/decrement (--x).

Hence x++ (value 10) should be executed before --x (value 11-1=10); so y=20. But How does 'y' become 18?

maanick90
  • 133
  • 1
  • 2
  • 12
  • 2
    See also http://stackoverflow.com/questions/2371118/how-do-the-post-increment-i-and-pre-increment-i-operators-work-in-java – Tunaki Aug 21 '16 at 18:27
  • 1
    I don’t know what they mean by higher precedence in that tutorial; it certainly isn’t relevant here. The operands of `+` are evaluated left to right, so `--x` is evaluated before `x++`. @Tunaki’s link is very useful for more detail. – Ole V.V. Aug 21 '16 at 19:12
  • What interested me at first was what is the point of having `a++` before `++a` since `++a++` is incorrect since both `++` will return value, but they expect variable so one of them simply will cause exception regardless if it will be compiled as `(++a)++` or `++(a++)`. But if I am not mistaken it comes handy in case of `a+++b` to determine that it is `(a++)+b` and not `a+(++b)`. – Pshemo Aug 21 '16 at 19:23

1 Answers1

3

As it is explained at this link

Associativity and precedence determine in which order Java applies operators to subexpressions but they do not determine in which order the subexpressions are evaluated. In Java, subexpressions are evaluated from left to right (when there is a choice). So, for example in the expression A() + B() * C(D(), E()), the subexpressions are evaluated in the order A(), B(), D(), E(), and C(). Although, C() appears to the left of both D() and E(), we need the results of both D() and E() to evaluate C(). It is considered poor style to write code that relies upon this behavior (and different programming languages may use different rules).

This explains why

--x

is executed and evaluated before than

x++

as it is a sum of two sub-expressions and the whole expression is evaluated from left to right. So the first one is executed before than the x++ one (yes, the post-fix ++ has more precedence in general, but here the sub-expression that includes it is evaluated after the first one).

So, 18 is correct, as you are summing two times 9 to x, as clarified below

x=10;
y = --x + x++;
// y = (10-1) /* now x==9 */ + (9); /* after this x == 10 */
// y = (9) + (9); /* and now x == 10 */
// y == 18 and x == 10
ddb
  • 2,423
  • 7
  • 28
  • 38