Java Reference
In-Depth Information
to create a new Boolean value. Table 3.3 lists the Boolean operators. Table 3.4 defines the not
(
!
) operator, which negates
true
to
false
and
false
to
true
. Table 3.5 defines the and
(
&&
) operator. The and (
&&
) of two Boolean operands is
true
if and only if both operands are
true
. Table 3.6 defines the or (
||
) operator. The or (
||
) of two Boolean operands is
true
if
at least one of the operands is
true
. Table 3.7 defines the exclusive or (
^
) operator. The
exclusive or (
^
) of two Boolean operands is
true
if and only if the two operands have differ-
ent Boolean values. Note that
p1 ^ p2
is the same as
p1 != p2
.
T
ABLE
3.3
Boolean Operators
Operator
Name
Description
!
not
logical negation
&&
and
logical conjunction
||
or
logical disjunction
^
exclusive or
logical exclusion
T
ABLE
3.4
Truth Table for Operator
!
p
!p
Example (assume
age = 24, gender = 'F'
)
true
false
!(age > 18)
is
false
, because
(age > 18)
is
true
.
false
true
!(gender == 'M')
is
true
, because
(gender == 'M')
is
false
.
T
ABLE
3.5
Truth Table for Operator
&&
p
1
p
2
p
1
&& p
2
Example (assume
age = 24, gender = 'F'
)
false
false
(age > 18) && (gender == 'F')
is
true
,
because
(age > 18)
and
(gender == 'F')
are
both
true
.
false
false
true
false
true
false
false
(age > 18) && (gender != 'F')
is
false
,
because
(gender != 'F')
is
false
.
true
true
true
T
ABLE
3.6
Truth Table for Operator
||
p
1
p
2
p
1
|| p
2
Example (assume
age = 24, gender = 'F'
)
false false
(age > 34) || (gender == 'F')
is
true
, because
(gender == 'F')
is
true
.
false
false true
true
true
false true
(age > 34) || (gender == 'M')
is
false
, because
(age
> 34)
and
(gender == 'M')
are both
false
.
true
true
true