Often in a program you need to compare two values, such as whether i is greater than j . Java provides six comparison operators (also known as relational operators ), shown in Table 3.1, which can be used to compare two values. The result of the comparison is a Boolean value: true or false . For example, the following statement displays true :
System.out.println( 1 < 2 );
Operator | Name | Example | Answer |
---|---|---|---|
< | less than | 1 < 2 | true |
<= | less than or equal to | 1 <= 2 | true |
> | greater than | 1 > 2 | false |
>= | greater than or equal to | 1 >= 2 | false |
== | equal to | 1 == 2 | false |
!= | not equal to | 1 != 2 | true |
Note
You can also compare characters . Comparing characters is the same as comparing the Unicodes of the characters. For example, ' a ' is larger than ' A ' because the Unicode of ' a ' is larger than the Unicode of ' A .' |
Caution
The equality comparison operator is two equal signs ( == ), not a single equal sign ( = ). The latter symbol is for assignment. |
A variable that holds a Boolean value is known as a Boolean variable . The boolean data type is used to declare Boolean variables . The domain of the boolean type consists of two literal values: true and false . For example, the following statement assigns true to the variable lightsOn :
boolean lightsOn = true ;
Boolean operators , also known as logical operators , operate on Boolean values to create a new Boolean value. Table 3.2 contains a list of Boolean operators. Table 3.3 defines the not ( ! ) operator. The not ( ! ) operator negates true to false and false to true . Table 3.4 defines the and ( && ) operator. The and ( && ) of two Boolean operands is true if and only if both operands are true . Table 3.5 defines the or ( ) operator. The or ( ) of two Boolean operands is true if at least one of the operands is true . Table 3.6 defines the exclusive or ( ^ ) operator. The exclusive or ( ^ ) of two Boolean operands is true if and only if the two operands have different Boolean values.
Operator | Name | Description |
---|---|---|
! | not | logical negation |
&& | and | logical conjunction |
or | logical disjunction | |
^ | exclusive or | logical exclusion |
p | !p | Example |
---|---|---|
true | false | !(1 > 2) is true , because (1 > 2) is false . |
false | true | !(1 > 0) is false , because (1 > 0) is true . |
p1 | p2 | p1 && p2 | Example |
---|---|---|---|
false | false | false | (2 > 3) && (5 > 5) is false , because either (2 > 3) or (5 > 5) is false . |
false | true | false | |
true | false | false | (3 > 2) && (5 > 5) is false , because (5 > 5) is false . |
true | true | true | (3 > 2) && (5 >= 5) is true , because (3 > 2) and (5 >= 5) are both true . |
p1 | p2 | p1 p2 | Example |
---|---|---|---|
false | false | false | (2 > 3)(5 > 5) is false , because (2 > 3) and (5 > 5) are both false . |
false | true | true | |
true | false | true | (3 > 2)(5 > 5) is true , because (3 > 2) is true . |
true | true | true |
p1 | p2 | p1^p2 | Example |
---|---|---|---|
false | false | false | (2 > 3) ^ (5 > 5) is true , because (2 > 3) is false and (5 > 1) is true . |
false | true | true | |
true | false | true | (3 > 2) ^ (5 > 1) is false , because both (3 > 2) and (5 > 1) are true . |
true | true | false |
Listing 3.1 gives a program that checks whether a number is divisible by 2 and 3 , whether a number is divisible by 2 or 3 , and whether a number is divisible by 2 or 3 but not both:
1 import javax.swin ptionPane; 2 3 public class TestBoolean { 4 public static void main(String[] args) { 5 int number = 18 ; 6 7 JOptionPane.showMessageDialog( null , 8 "Is " + number + 9 " \n divisible by 2 and 3? " + 10 (number % 2 == && number % 3 == ) 11 + " \n divisible by 2 or 3? " + 12 (number % 2 == number % 3 == ) + 13 " \n divisible by 2 or 3, but not both? " 14 + (number % 2 == ^ number % 3 == )); 15 } 16 }
|
A long string is formed by concatenating the substrings in lines 8 “14. The three \n characters display the string in four lines. (number % 2 == 0 && number % 3 == 0) (line 10) checks whether the number is divisible by 2 and 3. (number % 2 == 0 number % 3 == 0) (line 12) checks whether the number is divisible by 2 or 3. (number % 2 == 0 ^ number % 3 == 0) (line 14) checks whether the number is divisible by 2 or 3 , but not both.
If one of the operands of an && operator is false , the expression is false ; if one of the operands of an operand 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 evaluates p2 if p1 is true ; if p1 is false , it does not evaluate p2 . When evaluating p1 p2 , Java first evaluates p1 and then evaluates p2 if p1 is false ; 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 & and operators. The & operator works exactly the same as the && operator, and the operator works exactly the same as the operator with one exception: the & and operators always evaluate both operands. Therefore, & is referred to as the unconditional AND operator, and is referred to as the unconditional OR operator. In some rare situations when needed, you can use the & and operators to guarantee that the right-hand operand is evaluated regardless of whether the left-hand operand is true or false . For example, the expression (width < 2) & (height “ “ < 2) guarantees that (height “ “ < 2) is evaluated. Thus the variable height will be decremented regardless of whether width is less than 2 or not.
Tip
Avoid using the & and operators. The benefits of the & and operators are marginal. Using them will make the program difficult to read and could cause errors. For example, the expression (x != 0) & (100 / x) results in a runtime error if x is 0. However, (x != 0) && (100 / x) is fine. If x is , (x != 0) is false. Since && is a short-circuit operator, Java does not evaluate (100 / x) and returns the result as false for the entire expression (x != 0) && (100 / x). |
Note
The & and operators can also apply to bitwise operations . See Appendix G, "Bit Manipulations," for details. |
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 other types, nor can a value of other types be cast into a Boolean value. |
Note
true and false are literals, just like a number such as 10 , so they are not keywords, but you cannot use them as identifiers, just as you cannot use 10 as an identifier. |
This section presents a program that lets the user enter a year in a dialog box and checks whether it is a leap year.
A year is a leap year if it is divisible by 4 but not by 100 or if it is divisible by 400 . So you can use the following Boolean expression to check whether a year is a leap year:
(year % 4 == && year % 100 != ) (year % 400 == )
Listing 3.2 gives the program. Two sample runs of the program are shown in Figure 3.1.
1 import javax.swing.JOptionPane; 2 3 public class LeapYear { 4 public static void main(String args[]) { 5 // Prompt the user to enter a year 6 String yearString = JOptionPane.showInputDialog ( "Enter a year" ); 7 8 // Convert the string into an int value 9 int year = Integer.parseInt(yearString); 10 11 // Check if the year is a leap year 12 boolean isLeapYear = 13 (year % 4 == && year % 100 != ) (year % 400 == ); 14 15 // Display the result in a message dialog box 16 JOptionPane.showMessageDialog( null , 17 year + " is a leap year? " + isLeapYear); 18 } 19 } |
This example creates a program to let a first grader practice addition. The program randomly generates two single-digit integers number1 and number2 and displays a question such as "What is 7 + 9?" to the student, as shown in Figure 3.2(a). After the student types the answer in the input dialog box, the program displays a message dialog box to indicate whether the answer is true or false, as shown in Figure 3.2(b).
There are many good ways to generate random numbers . For now, generate the first integer using System.currentTimeMillis() % 10 and the second using System.currentTimeMillis() * 7 % 10 . Listing 3.3 gives the program. Lines 5 “6 generate two numbers, number1 and number2 . Line 11 displays a dialog box and obtains an answer from the user. The answer is graded in line 15 using a Boolean expression number1 + number2 == answer .
1 import javax.swing.*; 2 3 public class AdditionTutor { 4 public static void main(String[] args) { 5 int number1 = ( int )(System.currentTimeMillis() % 10 ); 6 int number2 = ( int )(System.currentTimeMillis() * 7 % 10 ); 7 8 String answerString = JOptionPane.showInputDialog 9 ( "What is " + number1 + " + " + number2 + "?" ); 10 11 int answer = Integer.parseInt(answerString); 12 13 JOptionPane.showMessageDialog( null , 14 number1 + " + " + number2 + " = " + answer + " is " + 15 ( number1 + number2 == answer )); 16 } 17 } |