Java Reference
In-Depth Information
Precedence and Associativity Rules
Boolean expressions (and arithmetic expressions) need not be fully parenthesized. If you
omit parentheses, Java follows precedence rules and associativity rules in place of the
missing parentheses. One easy way to think of the process is to think of the computer
adding parentheses according to these precedence and associativity rules. Some of
the Java precedence and associativity rules are given in Display 3.6. (A complete set
of precedence and associativity rules is given in Appendix 2 .) The computer uses
precedence rules to decide where to insert parentheses, but the precedence rules do
not differentiate between two operators at the same precedence level, in which case the
computer uses the associativity rules to “break the tie.”
If one operator occurs higher on the list than another in the precedence table
(Display 3.6), the higher one is said to have higher precedence . If one operator has
higher precedence than another, the operator of higher precedence is grouped with its
operands (its arguments) before the operator of lower precedence. For example, if the
computer is faced with the expression
precedence
rules
associativity
rules
higher
precedence
balance * rate + bonus
it notices that * has a higher precedence than + , so it first groups * and its operands,
as follows:
(balance * rate) + bonus
Next, it groups + with its operands to obtain the fully parenthesized expression
((balance * rate) + bonus)
Sometimes two operators have the same precedence, in which case the parentheses
are added using the associativity rules. To illustrate this, let's consider another example:
bonus + balance * rate / correctionFactor - penalty
The operators * and / have higher precedence than either + or - , so * and / are grouped
first. But * and / have equal precedence, so the computer consults the associativity rule
for * and / , which says they associate from left to right. This means that the * , which
is the leftmost of * and / , is grouped first. So the computer interprets the expression as
bonus + (balance * rate) / correctionFactor - penalty
which in turn is interpreted as
bonus + ((balance * rate) / correctionFactor) - penalty
because / has higher precedence than either + or - .
This expression is still not fully parenthesized, however. The computer still must
choose to group + first or - first. According to Display 3.6 , + and - have equal precedence.
 
Search WWH ::




Custom Search