Java Reference
In-Depth Information
tableĀ 2-11: Logical Operators
logical oper ator
meaning
ex amples
result
Conditional AND operator: True if both
operands are true.
False
&&
A && B
Conditional OR operator: True if at least
one operand is true.
True
||
A || B
Bitwise and Logical XOR operator: True if
one, and only one, operand is true.
True
^
A ^ B
Unary NOT operator: True if the operand is
false.
False
!
!A
The truth tables for these Boolean operators are illustrated in Table 2-12. Table 2-12 assumes two
operands that may be either true or false, as indicated by the first and second column.
tableĀ 2-12: Truth Table for Logical Operators
oper and 1
oper and 2
and
or
xor
not (oper and 1)
True
True
True
True
False
False
True
False
False
True
True
False
False
True
False
False
True
True
False
False
False
False
False
True
The bitwise AND ( & ) and OR ( | ) operators can also be used with Boolean operands. However, there
is a difference between the conditional and bitwise operators. If the first operand evaluates to false,
the conditional AND operator ( && ) will not consider the second operand, since it already knows the
outcome will be false. This is often referred to as short-circuiting behavior. The bitwise AND opera-
tor ( & ) always evaluates both operands. Similarly, if the first operand evaluates to true, the condi-
tional OR operator ( || ) will no longer evaluate the second operand, since it already knows that the
outcome will be true. The bitwise OR operator ( | ) always evaluates both operands.
This means that using the conditional ( && ) and ( || ) operators can lead to more efficient program
executions. But that is not the only reason to use the conditional operators. If evaluating an expres-
sion may lead to an error, taking advantage of the short-circuiting feature can prevent this by ignor-
ing the error-prone expression in cases where the error would occur. For example, trying to divide
a number by 0 will cause an error. So you could use the conditional AND ( && ) to first check if the
number is not zero and then check the result of dividing by it only if it is, in fact, not zero. If it is
zero, the second expression will not be evaluated.
Search WWH ::




Custom Search