Java Reference
In-Depth Information
Next, we evaluate subexpressions left to right. (6 evaluates to 6 and 7 evaluates to 7,
but that's so obvious we will not make a big deal of it.) The variable n evaluates to 2.
(Remember, we assumed the value of n was 2.) So, we can rewrite the expression as
((6 + (7 * 2)) - 12)
The * is the only operator that has both of its operands evaluated, so it evaluates to 14
to produce
((6 + 14) - 12)
Now + has both of its operands evaluated, so (6 + 14) evaluates to 20 to yield
(20 - 12)
which in turn evaluates to 8. So 8 is the value for the entire expression.
This may seem like more work than it should be, but remember, the computer is
following an algorithm and proceeds step by step; it does not get inspired to make
simplifying assumptions.
Next, let's consider an expression with side effects. In fact, let's consider the one we
fully parenthesized earlier. Consider the following fully parenthesized expression and
assume the value of n is 2:
((result = (++n)) + (other = (2*(++n))))
Subexpressions are evaluated left to right. So, result is evaluated first. When used
with the assignment operator = , a variable simply evaluates to itself. So, result is eval-
uated and waiting. Next, ++n is evaluated, and it returns the value 3. The expression is
now known to be equivalent to
((result = 3) + (other = (2*(++n))))
Now the assignment operator = has its two operands evaluated, so (result = 3) is
evaluated. Evaluating (result = 3) sets the value of result equal to 3 and returns the
value 3. Thus, the expression is now known to be equivalent to
(3 + (other = (2*(++n))))
(and the side effect of setting result equal to 3 has happened). Proceeding left to
right, the next thing to evaluate is the variable other , which simply evaluates to itself,
so you need not rewrite anything.
Proceeding left to right, the next subexpression that can be evaluated is n , which
evaluates to 3. (Remember, n has already been incremented once, so n now has the
value 3.) Then ++ has its only argument evaluated, so it is ready to be evaluated. The
evaluation of (++n) has the side effect of setting n equal to 4 and evaluates to 4. So, the
entire expression is equivalent to
(3 + (other = (2*4)))
Search WWH ::




Custom Search