Java Reference
In-Depth Information
}
This code works but the logic of the method is almost completely lost in
the nested
ifelse
statements ensuring the array is non-empty. To avoid
the need for two
if
statements, we could try to test whether the argu-
ment is
null
or
whether it has a zero length, by using the boolean in-
clusive-
OR
operator (
|
):
if (values == null | values.length == 0)
throw new IllegalArgumentException();
Unfortunately, this code is not correct. Even if
values
is
null
, this code
will still attempt to access its
length
field because the normal boolean
operators always evaluate both operands. This situation is so common
when performing logical operations that special operators are defined to
solve it. The conditional boolean operators evaluate their right-hand op-
erand only if the value of the expression has not already been determin-
ed by the left-hand operand. We can correct the example code by using
the conditional-
OR
(
||
) operator:
if (values == null || values.length == 0)
throw new IllegalArgumentException();
Now if
values
is
null
the value of the conditional-
OR
expression is known
to be
true
and so no attempt is made to access the
length
field.
The binary boolean operators
AND
(
&
), inclusive-
OR
(
|
), and exclusive-
OR
(
^
)are logical operators when their operands are boolean values and bit-
wise operators when their operands are integer values. The condition-
al-
OR
(
||
) and conditional-
AND
(
&&
) operators are logical operators and
can only be used with boolean operands.