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