Java Reference
In-Depth Information
increase efficiency, the Java interpreter takes a shortcut and skips the second
operand. The second operand is not guaranteed to be evaluated, so you must
use caution when using this operator with expressions that have side effects.
On the other hand, the conditional nature of this operator allows us to write
Java expressions such as the following:
if ( data != null && i < data . length && data [ i ] != - 1 )
...
The second and third comparisons in this expression would cause errors if the
first or second comparisons evaluated to false . Fortunately, we don't have to
worry about this because of the conditional behavior of the && operator.
Conditional OR ( || )
This operator performs a Boolean OR operation on its two boolean operands.
It evaluates to true if either or both of its operands are true . If both operands
are false , it evaluates to false . Like the && operator, || does not always evaluā€
ate its second operand. If the first operand evaluates to true , the value of the
expression is true , regardless of the value of the second operand. Thus, the
operator simply skips the second operand in that case.
Boolean NOT ( ! )
This unary operator changes the boolean value of its operand. If applied to a
true value, it evaluates to false , and if applied to a false value, it evaluates to
true . It is useful in expressions like these:
if (! found ) ... // found is a boolean declared somewhere
while (! c . isEmpty ()) ... // The isEmpty() method returns a boolean
Because ! is a unary operator, it has a high precedence and often must be used
with parentheses:
if (!( x > y && y > z ))
Boolean AND ( & )
When used with boolean operands, the & operator behaves like the && operator,
except that it always evaluates both operands, regardless of the value of the first
operand. This operator is almost always used as a bitwise operator with integer
operands, however, and many Java programmers would not even recognize its
use with boolean operands as legal Java code.
Boolean OR ( | )
This operator performs a Boolean OR operation on its two boolean operands.
It is like the || operator, except that it always evaluates both operands, even if
the first one is true . The | operator is almost always used as a bitwise operator
on integer operands; its use with boolean operands is very rare.
Boolean XOR ( ^ )
When used with boolean operands, this operator computes the exclusive OR
(XOR) of its operands. It evaluates to true if exactly one of the two operands is
Search WWH ::




Custom Search