Java Reference
In-Depth Information
T
ABLE
3.7
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
(age > 34)
is
false
but
(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
false
Listing 3.7 gives a program that checks whether a number is divisible by
2
and
3
, by
2
or
3
, and by
2
or
3
but not both:
L
ISTING
3.7
TestBooleanOperators.java
1
import
java.util.Scanner;
2
3
public class
TestBooleanOperators {
4
public static void
main(String[] args) {
5
// Create a Scanner
6 Scanner input =
new
Scanner(System.in);
7
8
// Receive an input
9 System.out.print(
"Enter an integer: "
);
10
11
12
if
(number %
2
== 0 number %
3
==
0
)
13 System.out.println(number +
" is divisible by 2 and 3."
);
14
15
if
(number %
2
==
0
number %
3
==
0
)
16 System.out.println(number +
" is divisible by 2 or 3."
);
17
18
if
(number %
2
==
0
number %
3
==
0
)
19 System.out.println(number +
20
import class
int
number = input.nextInt();
input
&&
and
||
or
^
exclusive or
" is divisible by 2 or 3, but not both."
);
21 }
22 }
Enter an integer:
4 is divisible by 2 or 3.
4 is divisible by 2 or 3, but not both.
4
Enter an integer:
18 is divisible by 2 and 3.
18 is divisible by 2 or 3.
18
(number % 2 == 0 && number % 3 == 0)
(line 12) checks whether the number is
divisible by both
2
and
3
.
(number % 2 == 0 || number % 3 == 0)
(line 15) checks
whether the number is divisible by
2
and/or by
3
.
(number % 2 == 0 ^ number % 3 ==
0)
(line 18) checks whether the number is divisible by
2
or
3
, but not both.
Caution
In mathematics, the expression
1
<= numberOfDaysInAMonth <=
31