Java Reference
In-Depth Information
T ABLE 3.5
Truth Table fo r Operator &&
p 1
p 2
p 1 && p 2
Example (assume age = 24, weight = 140 )
false
false
false
(age > 28) && (weight <= 140) is true ,
because (age > 28) is false .
false
true
false
true
false
false
(age > 18) && (weight >= 140) is true ,
because (age > 18) and (weight >= 140) are
both true .
true
true
true
T ABLE 3.6
Truth Table for Operator ||
p 1
p 2
p 1 || p 2
Example (assume age = 24, weight = 140 )
false
false false
(age > 34) || (weight >= 150) is false , because
(age > 34) and (weight >= 150) are both false .
false
true
true
true
false true
(age > 18) || (weight < 140) is true , because
(age > 18) is true .
true
true
true
T ABLE 3.7
Truth Table for Operator ^
p 1
p 2
p 1 ^ p 2
Example (assume age = 24, weight = 140 )
false false false
(age > 34) ^ (weight > 140) is false , because (age > 34) and
(weight > 140) are both false .
false true
true
(age > 34) ^ (weight >= 140) is true , because (age > 34) is
false but (weight >= 140) is true .
true
false true
true
true
false
Listing 3.6 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.6
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
import class
int number = input.nextInt();
input
11
12 if (number % 2 == 0 && number % 3 == 0 )
13 System.out.println(number + " is divisible by 2 and 3." );
14
and
 
 
Search WWH ::




Custom Search