Java Reference
In-Depth Information
Boolean Logical Exclusive OR ( ^ )
A simple condition containing the boolean logical exclusive OR ( ^ ) operator is true if and
only if one of its operands is true and the other is false . If both are true or both are false ,
the entire condition is false . Figure 5.17 is a truth table for the boolean logical exclusive
OR operator ( ^ ). This operator is guaranteed to evaluate both of its operands.
expression1
expression2
expression1 ^ expression2
false
false
false
false
true
true
true
false
true
true
true
false
Fig. 5.17 | ^ (boolean logical exclusive OR) operator truth table.
Logical Negation ( ! ) Operator
The ! ( logical NOT , also called logical negation or logical complement ) operator “revers-
es” the meaning of a condition. Unlike the logical operators && , || , & , | and ^ , which are
binary operators that combine two conditions, the logical negation operator is a unary op-
erator that has only one condition as an operand. The operator is placed before a condition
to choose a path of execution if the original condition (without the logical negation oper-
ator) is false , as in the program segment
if (! (grade == sentinelValue))
System.out.printf( "The next grade is %d%n" , grade);
which executes the printf call only if grade is not equal to sentinelValue . The paren-
theses around the condition grade == sentinelValue are needed because the logical ne-
gation operator has a higher precedence than the equality operator.
In most cases, you can avoid using logical negation by expressing the condition dif-
ferently with an appropriate relational or equality operator. For example, the previous
statement may also be written as follows:
if (grade != sentinelValue)
System.out.printf( "The next grade is %d%n" , grade);
This flexibility can help you express a condition in a more convenient manner. Figure 5.18
is a truth table for the logical negation operator.
expression
! expression
false
true
true
false
Fig. 5.18 | ! (logical NOT) operator truth table.
Logical Operators Example
Figure 5.19 uses logical operators to produce the truth tables discussed in this section.
The output shows the boolean expression that was evaluated and its result. We used the
 
Search WWH ::




Custom Search