There are two different things here: expression parsing and expression.
Let's start with the expression: ++a + ++a * ++a . What should we do first? Since the operators + and * need two operands, and ++ needs one operand, we need to find out which operand goes with which operation. This is an expression parsing step that applies priority / associativity.
++ has the highest priority, so we can rewrite our expression as (++a) + (++a) * (++a)- Then do
* , so you can add parentheses again: (++a) + ((++a) * (++a)) - And finally,
+ , the lowest priority for everyone, so for symmetry we can write: ((++a) + ((++a) * (++a)))
Note that we can represent this neatly as a tree:
+ / \ ++ * | | \ a ++ ++ | | aa
So this is our rating tree based on priority and associativity.
Note that in this case associativity does not matter at all, since all operators had a different priority. If our expression were 4 - 1 - 3 + 2 , it would be important to use associativity to achieve (((4 - 1) - 3) + 2) , since + and - have the same priority.
Now comes the next step, assessment. Evaluation always happens from left to right (even for appointments, although the rules are a bit fancy), but it happens from left to right using the tree just built.
- So, first we begin to evaluate the
+ operator as it is on top. - Then we go one level down to the left, because we evaluate
++a on the left side of the + operator, (6) - then we go right and begin to evaluate the operation
* . - The way we do this is to evaluate the second
++a , (7) - then the third
++a (8) - and then multiply the result of steps 4 and 5 (this is the operation
* ), (56) - and finally add the result of step 6 to the result of step 2 (62)
... and we are done.
TL DR . Priority and associativity determine where to put parentheses, but the score is always from left to right.
15.7. Assessment Procedure
The Java programming language ensures that the operands of the operators are apparently evaluated in a specific evaluation order, namely, from left to right.
source share