Java Reference
In-Depth Information
Any arithmetic operators at the same level of precedence are performed left to
right. Therefore we say the arithmetic operators have a left-to-right association.
Precedence, however, can be forced in an expression by using parentheses. For
instance, if we really wanted the addition to be performed first in the previous
example, we could write the expression as follows:
result = (14 + 8) / 2;
Any expression in parentheses is evaluated first. In complicated expressions, it
is good practice to use parentheses, even when it is not strictly necessary, to make
it clear how the expression is evaluated.
Parentheses can be nested, and the innermost nested expressions are evaluated
first. Consider the following expression:
result = 3 * ((18 - 4) / 2);
In this example, the result is 21 . First, the subtraction is performed, forced by
the inner parentheses. Then, even though multiplication and division are at the
same level of precedence and usually would be evaluated left to right, the division
is performed first because of the outer parentheses. Finally, the multiplication is
performed.
After the arithmetic operations are complete, the computed result is stored
in the variable on the left-hand side of the assignment operator ( = ). In other
words, the assignment operator has a lower precedence than any of the arith-
metic operators.
The evaluation of a particular expression can be shown using an expression
tree, such as the one in Figure 2.3. The operators are executed from the bottom
up, creating values that are used in the rest of the expression. Therefore, the
operations lower in the tree have a higher precedence than those above, or they
are forced to be executed earlier using parentheses.
+
a
/
Evaluating
a + (b - c) / d
-
d
b
c
FIGURE 2.3
An expression tree
 
Search WWH ::




Custom Search