Java Reference
In-Depth Information
expression1
expression2
expression1
||
expression2
false
false
false
false
true
true
true
false
true
true
true
true
Fig. 5.16
|
||
(conditional OR) operator truth table.
Short-Circuit Evaluation of Complex Conditions
The parts of an expression containing
&&
or
||
operators are evaluated
only
until it's known
whether the condition is true or false. Thus, evaluation of the expression
(gender ==
FEMALE
) && (age >=
65)
stops immediately if
gender
is not
equal to
FEMALE
(i.e., the entire expression is
false
) and
continues if
gender
is
equal to
FEMALE
(i.e., the entire expression could still be
true
if the
condition
age
>=
65
is
true
). This feature of conditional AND and conditional OR ex-
pressions is called
short-circuit evaluation
.
Common Programming Error 5.8
In expressions using operator
&&
, a condition—we'll call this the
dependent condition
—
may require another condition to be true for the evaluation of the dependent condition to be
meaningful. In this case, the dependent condition should be placed
after
the
&&
operator to
prevent errors. Consider the expression
(i != 0) && (10 / i == 2)
. The dependent condition
(10/i==2)
must
appear after the
&&
operator to prevent the possibility of division by zero.
Boolean Logical AND (
&
) and Boolean Logical Inclusive OR (
|
) Operators
The
boolean logical AND
(
&
) and
boolean logical inclusive OR
(
|
)
operators are identical
to the
&&
and
||
operators, except that the
&
and
|
operators
always
evaluate
both
of their
operands (i.e., they do
not
perform short-circuit evaluation). So, the expression
(gender ==
1
) & (age >=
65
)
evaluates
age
>=
65
regardless
of whether
gender
is equal to
1
. This is useful if the right
operand has a required
side effect
—a modification of a variable's value. For example, the
expression
(birthday == true) | (++age >=
65
)
guarantees that the condition
++age
>=
65
will be evaluated. Thus, the variable
age
is in-
cremented, regardless of whether the overall expression is
true
or
false
.
Error-Prevention Tip 5.9
For clarity, avoid expressions with side effects (such as assignments) in conditions. They
can make code harder to understand and can lead to subtle logic errors.
Error-Prevention Tip 5.10
Assignment (
=
) expressions generally should
not
be used in conditions. Every condition
must
result in a
boolean
value; otherwise, a compilation error occurs. In a condition, an
assignment will compile
only
if a
boolean
expression is assigned to a
boolean
variable.