Programming and Problem Solving with Java

(やまだぃちぅ) #1
4.2 Conditions and Logical Expressions | 163

Value of x Value of y Value of (x || y)
true true true
true false true
false true true
false false false

The following table summarizes the results of applying the !operator to a logical ex-
pression (represented by the booleanvariable x).


Value of x Value of !x
true false
false true

Short-Circuit Evaluation Consider the logical expression


i == 1 && j > 2


Some programming languages use full evaluationto parse such a logical expres-
sion. With full evaluation, the computer first evaluates both subexpressions (both
i == 1 and j > 2) before applying the &&operator to produce the final result.
In contrast, Java uses short-circuit(or conditional) evaluationof logical expres-
sions. That is, evaluation proceeds from left to right, and the computer stops eval-
uating subexpressions as soon as possible—as soon as it knows the Boolean value
of the entire expression. How can the computer know if a lengthy logical ex-
pression yields trueor falseif it doesn’t examine all the subexpressions? Let’s look
first at the AND operation.
An AND operation yields the value trueonly if both of its operands are true.
In the preceding expression, suppose that the value of iis 95. The first subexpression yields
false, so it isn’t necessary to even look at the second subexpression. The computer stops eval-
uation and produces the final result of false.
With the OR operation, the left-to-right evaluation stops as soon as a subexpression
yielding trueis found. Recall that an OR produces a result of trueif either one or both of its
operands are true. Given the expression


c <= d || e == f


if the first subexpression is true, then evaluation stops and the entire result is true. The com-
puter doesn’t waste time evaluating the second subexpression.
Java provides a second set of logical operators that result in full evaluation of Boolean
expressions. The single &and |perform logical AND and OR operations, respectively, with full
evaluation. We don’t recommend their use at this stage in your experience with program-
ming. In Java these operators have another meaning with variables or constants of type byte,
short,int, or long, which can lead to errors that may prove difficult to find.


Short-circuit (conditional) eval-
uation Evaluation of a logical
expression in left-to-right order
with evaluation stopping as
soon as the final Boolean value
can be determined
Free download pdf