Java Reference
In-Depth Information
The only subexpression that has its operands evaluated is (2
*
4), so it is evaluated to 8
to produce
(3 + (other = 8))
Now the assignment operator
=
has both of its operands evaluated, so it evaluates to 8
and has the side effect of setting
other
equal to 8. Thus, we know the value of the
expression is
(3 + 8)
which evaluates to 11. So, the entire expression evaluates to 11 (and has the side effects
of setting
result
equal to 3, setting
n
equal to 4, and setting other equal to 8). These
rules also allow for method invocations in expressions. For example, in
(++n > 0) && (s.length( ) > n)
the variable
n
is incremented before
n
is compared to
s
.
length( )
. When we start
defining and using more methods, you will see less-contrived examples of expressions
that include method invocations.
All of these rules for evaluating expressions are summarized in the box entitled
“Rules for Evaluating Expressions.”
Rules for Evaluating Expressions
Expressions are evaluated as follows:
1.
Binding: Determine the equivalent fully parenthesized expression using the precedence
and associativity rules.
2.
Proceeding left to right, evaluate whatever subexpressions you can evaluate. (These
subexpressions will be operands or method arguments. For example, in simple cases
they may be numeric constants or variables.)
3.
Evaluate each outer operation (and method invocation) as soon as all of its operands (all
its arguments) have been evaluated.
Self-Test Exercises
19. Determine the value,
true
or
false
, of each of the following Boolean expressions,
assuming that the value of the variable
count
is 0 and the value of the variable
limit
is 10. (Give your answer as one of the values
true
or
false
.)
a.
(count == 0) && (limit < 20)
b .
count == 0 && limit < 20
c .
(limit > 20)
||
(count < 5)
(continued)