According to this table, ++
has right to left associativity. So, I run this code:
int a = 5;
++a + ++a * ++a
and expect the expression to be 50
(as 8 + 7 * 6
, increment starts from right to left). But the expression is evaluated from left to right (6 + 7 * 8
) by Eclipse, and gives result as 62
. I am new to this associativity in Java, and must be missing something obvious. Please help me understand this strange behavior.
EDIT: Thank you for your answers, but I have one more question now. It is that, as seen from @bizclop's code and tree answer, it is obvious that the associativity for ++
doesn't matter. Then, is there any use case for this associativity of ++
/--
?
There are two different things mixed up here: expression parsing and expression evaluation.
Let's start with the expression:
++a + ++a * ++a
. What do we first have to do with it? Since operators+
and*
need two operands and++
needs one, we have to figure out which operand goes with which operation. This is the expression parsing step, where precedence/associativity are applied.++
has the highest precedence, so we can rewrite our expression as(++a) + (++a) * (++a)
*
, so again we can add parentheses:(++a) + ((++a) * (++a))
+
, the lowest precedence of all, so for the sake of symmetry we can write:((++a) + ((++a) * (++a)))
Note that we can represent this neatly as a tree:
So this is our evaluation tree based on precedence and associativity.
Now comes the next step, evaluation. Evaluation always happens from left to right (even for assignments, though the rules are a bit quirky), but it happens left-to-right using the tree we've just built.
+
operator, as it's on the top.++a
on the left side of the+
operator, (6)*
operation.++a
, (7)++a
(8)*
operation evaluated), (56)...and we're done.
TL;DR: Precedence and associativity determine where to put parentheses but evaluation is always left-to-right.