Operator precedence and associativity determine the order in which operators are evaluated.
Suppose that you have this expression:
3 + 4 * 4 > 5 * (4 + 3) – 1 && (4 - 3 > 5)
What is its value? What is the execution order of the operators?
The expression within parentheses is evaluated first. (Parentheses can be nested, in which case the expression within the inner parentheses is executed first.) When evaluating an expression without parentheses, the operators are applied according to the precedence rule and the associativity rule.
The precedence rule defines precedence for operators, as shown above. Operators are listed in decreasing order of precedence from top to bottom. The logical operators have lower precedence than the relational operators and the relational operators have lower precedence than the arithmetic operators. Operators with the same precedence appear in the same group.
If operators with the same precedence are next to each other, their associativity determines the order of evaluation. All binary operators except assignment operators are left associative. For example, since + and – are of the same precedence and are left associative, the expression
a - b + c – d is equivalent to ((a - b) + c) - d
Assignment operators are right associative. Therefore, the expression
a = b += c = 5 is equivalent to a = (b += (c = 5))
Suppose a, b, and c are 1 before the assignment; after the whole expression is evaluated, a becomes 6, b becomes 6, and c becomes 5. Note that left associativity for the assignment operator would not make sense.
Java has its own way to evaluate an expression internally. The result of a Java evaluation is the same as that of its corresponding arithmetic evaluation.
Top comments (0)