Java Reference
In-Depth Information
is correct. However, it is incorrect in Java, because
1 <= numberOfDaysInAMonth
is
evaluated to a
boolean
value, which cannot be compared with
31
. Here, two operands
(a
boolean
value and a numeric value) are
incompatible
. The correct expression in Java is
incompatible operands
(
1
<= numberOfDaysInAMonth) && (numberOfDaysInAMonth <=
31
)
Note
As shown in the preceding chapter, a
char
value can be cast into an
int
value, and
vice versa. A
boolean
value, however, cannot be cast into a value of another type, nor
can a value of another type be cast into a
boolean
value.
cannot cast
boolean
Note
De Morgan's law, named after Indian-born British mathematician and logician Augustus
De Morgan (1806-1871), can be used to simplify Boolean expressions. The law states:
De Morgan's law
!(condition1 && condition2)
is the same as
!condition1 || !condition2
!(condition1 || condition2)
is the same as
!condition1 && !condition2
For example,
!
(number %
2
==
0
&&
number %
3
==
0
)
can be simplified using an equivalent expression:
(number %
2
!=
0
|| number %
3
!=
0
)
As another example,
!(number ==
2
|| number ==
3
)
is better written as
number !=
2
&& number !=
3
If one of the operands of an
&&
operator is
false
, the expression is
false
; if one of the
operands of an
||
operator is
true
, the expression is
true
. Java uses these properties to improve
the performance of these operators. When evaluating
p1 && p2
, Java first evaluates
p1
and then,
if
p1
is
true
, evaluates
p2
; if
p1
is
false
, it does not evaluate
p2
. When evaluating
p1 || p2
,
Java first evaluates
p1
and then, if
p1
is
false
, evaluates
p2
; if
p1
is
true
, it does not evaluate
p2
. Therefore,
&&
is referred to as the
conditional
or
short-circuit AND
operator, and is
referred to as the
conditional
or
short-circuit OR
operator. Java also provides the conditional
AND (
&
) and OR (
|
) operators, which are covered in Supplement III.C and III.D for advanced
readers.
conditional operator
short-circuit operator
3.18
✓
✓
Assuming that
x
is
1
, show the result of the following Boolean expressions.
Check
Point
(
true
) && (
3
>
4
)
!(x >
0
) && (x >
0
)
(x >
0
) || (x <
0
)
(x !=
0
) || (x ==
0
)
(x >=
0
) || (x <
0
)
(x !=
1
) == !(x ==
1
)
3.19
Write a Boolean expression that evaluates to
true
if a number stored in variable
num
is between
1
and
100
.
3.20
Write a Boolean expression that evaluates to
true
if a number stored in variable
num
is between
1
and
100
or the number is negative.