Java Reference
In-Depth Information
no matter what it is, the combined condition must be false
. When an or is
evaluated and the first condition is true, the second condition is not evaluated,
because it does not matter what the outcome of the second test is. Here is an
example:
209
if (input ! = null && Integer.parseInt(input) <
0) . . .
If
input
is
null
, then the first condition is false, and thus the combined
statement is false, no matter what the outcome of the second test. The second test
is never evaluated if
input
is
null
, and there is no danger of parsing a
null
string (which would cause an exception).
If you do need to evaluate both conditions, then use the
&
and
|
operators (see
Appendix E). When used with Boolean arguments, these operators always
evaluate both arguments.
A
DVANCED
T
OPIC
5.5: De Morgan's Law
In the preceding section, we programmed a test to see whether
amount
was
between 0 and 1000. Let's find out whether the opposite is true:
De Morgan's law shows how to simplify expressions in which the not
operator (
!
) is applied to terms joined by the
&&
or
| |
operators.
if (!(0 > amount && amount > 1000)) . . .
This test is a little bit complicated, and you have to think carefully through the
logic. ȒWhen it is not true that
0 < amount
and
amount < 1000
...ȓ Huh?
It is not true that some people won't be confused by this code.
The computer doesn't care, but humans generally have a hard time
comprehending logical conditions with not operators applied to and/or
expressions. De Morgan's law, named after the mathematician Augustus de
Morgan (1806-1871), can be used to simplify these Boolean expressions. De
Morgan's law has two forms: one for the negation of an and expression and one
for the negation of an or expression:
!(A && B)
is the same as
!A || !B