Java Reference
In-Depth Information
a
!a
false
true
true
false
FIGURE 5.3 Truth table describing the logical NOT operator
NOT operator is unary, there are only two possible values for its one operand:
true or false. Figure 5.3 shows a truth table that describes the ! operator.
The && operator performs a logical AND operation. The result is true if both
operands are true, but false otherwise. Compare that to the result of the
logical
OR operator ( || ), which is true if one or the other or both operands are true, but
false otherwise.
The AND and OR operators are both binary operators since each uses two oper-
ands. Therefore, there are four possible combinations to consider: both operands
are true, both are false, one is true and the other false, and vice versa. Figure 5.4
depicts a truth table that shows both the && and || operators.
The logical NOT has the highest precedence of the three logical operators, fol-
lowed by logical AND, then logical OR.
Consider the following if statement:
if (!done && (count > MAX))
System.out.println ("Completed.");
Under what conditions would the println statement be executed? The value of
the boolean variable done is either true or false, and the NOT operator reverses
that value. The value of count is either greater than MAX or it isn't. The truth table
in Figure 5.5 breaks down all of the possibilities.
An important characteristic of the && and || operators is that
they are “short-circuited.” That is, if their left operand is sufficient
to decide the boolean result of the operation, the right operand is
not evaluated. This situation can occur with both operators, but for
KEY CONCEPT
Logical operators are often used to
construct sophisticated conditions.
a || b
a
b
a && b
false
false
false
true
false
false
false
true
true
true
false
true
false
true
true
true
FIGURE 5.4 Truth table describing the logical AND and OR operators
 
Search WWH ::




Custom Search