Java Reference
In-Depth Information
that determine how the operators, such as + and * , are enclosed in parentheses. These
precedence rules are similar to rules used in algebra. For example,
base + rate * hours
is evaluated by Java as if it were parenthesized as follows:
base + (rate * hours)
So, the multiplication will be done before the addition.
Except in some standard cases, such as a string of additions or a simple multiplication
embedded inside an addition, it is usually best to include the parentheses, even if the
intended groupings are the ones dictated by the precedence rules. The parentheses
make the expression easier to read and less prone to programmer error.
A partial list of precedence rules is given in Display 1.3. A complete set of Java
precedence rules is given in Appendix 2. Operators that are listed higher on the list are
said to have higher precedence . When the computer is deciding which of two adjacent
operations to group with parentheses, it groups the operation of higher precedence and
its apparent arguments before the operation of lower precedence. Some operators have
equal precedence, in which case the order of operations is determined by associativity
rules . A brief summary of associativity rules is that binary operators of equal precedence
are grouped in left-to-right order. 5 Unary operators of equal precedence are grouped in
right-to-left order. So, for example,
base + rate + hours
is interpreted by Java to be the same as
(base + rate) + hours
And, for example,
+-+rate
is interpreted by Java to be the same as
+(-(+rate))
For now you can think of the explicit parentheses put in by the programmer and the
implicit parentheses determined by precedence and associativity rules as determining
the order in which operations are performed. For example, in
base + (rate * hours)
the multiplication is performed first and the addition is performed second.
5 There is one exception to this rule. A string of assignment operators, such as n1 = n2 = n3; , is
performed right to left, as we noted earlier in this chapter.
 
Search WWH ::




Custom Search