Java Reference
In-Depth Information
For an expression with no side effects, the rule of performing inner parenthesized
expressions before outer ones is all you need. That rule will get you through most sim-
ple expressions, but for expressions with side effects, you need to learn the rest of the
story, which is what we will do next.
The complications come from the fact that some expressions have side effects . When
we say an expression has side effects , we mean that in addition to returning a value,
the expression also changes something, such as the value of a variable. Expressions
with the assignment operator have side effects; pay = bonus , for example, changes the
value of pay . Increment and decrement operators have side effects; ++n changes the
value of n . In expressions that include operators with side effects, you need more rules.
For example, consider
side effects
((result = (++n)) + (other = (2*(++n))))
The parentheses seem to say that you or the computer should first evaluate the two
increment operators, ++n and ++n , but the parentheses do not say which of the two ++n 's
to do first. If n has the value 2 and we evaluate the leftmost ++n first, then the variable
result is set to 3 and the variable other is set to 8 (and the entire expression evaluates to
11). But if we evaluate the rightmost ++n first, then other is set to 6 and result is set to
4 (and the entire expression evaluates to 10). We need a rule to determine the order of
evaluation when we have a tie like this. However, rather than simply adding a rule to
break such ties, Java instead takes a completely different approach.
To evaluate an expression, Java uses the following three rules:
1. Java first does binding; that is, it first fully parenthesizes the expression using
precedence and associativity rules, just as we have outlined.
2. Then it simply evaluates expressions left to right.
3. If an operator is waiting for its two (or one or three) operands to be evaluated,
then that operator is evaluated as soon as its operands have been evaluated.
We'll first do an example with no side effects and then an example of an expression
with side effects. First the simple example. Consider the expression
6 + 7 * n - 12
and assume the value of n is 2. Using the precedence and associativity rules, we add
parentheses one pair at a time as follows:
6 + (7 * n) - 12
then
(6 + (7 * n)) - 12
and finally the fully parenthesized version
((6 + (7 * n)) - 12)
Search WWH ::




Custom Search