The if, if...else, while, do...while and for statements each require a condition to determine how to continue a program's flow of control. So far, we have studied only simple conditions, such as count <= 10, number != sentinelValue and total > 1000. Simple conditions are expressed in terms of the relational operators >, <, >= and <= and the equality operators == and !=, and each expression tests only one condition. To test multiple conditions in the process of making a decision, we performed these tests in separate statements or in nested if or if...else statements. Sometimes, control statements require more complex conditions to determine a program's flow of control.
Java provides logical operators to enable programmers to form more complex conditions by combining simple conditions. The logical operators are && (conditional AND), || (conditional OR), & (boolean logical AND), | (boolean logical inclusive OR), ^ (boolean logical exclusive OR) and ! (logical NOT).
Conditional AND (&&) Operator
Suppose that we wish to ensure at some point in a program that two conditions are both true before we choose a certain path of execution. In this case, we can use the && (conditional AND) operator, as follows:
if ( gender == FEMALE && age >= 65 ) ++seniorFemales;
This if statement contains two simple conditions. The condition gender == FEMALE compares variable gender to the constant FEMALE. This might be evaluated, for example, to determine whether a person is female. The condition age >= 65 might be evaluated to determine whether a person is a senior citizen. The if statement considers the combined condition
gender == FEMALE && age >= 65
which is true if and only if both simple conditions are true. If the combined condition is true, the if statement's body increments seniorFemales by 1. If either or both of the simple conditions are false, the program skips the increment. Some programmers find that the preceding combined condition is more readable when redundant parentheses are added, as in:
( gender == FEMALE ) && ( age >= 65 )
The table in Fig. 5.14 summarizes the && operator. The table shows all four possible combinations of false and true values for expression1 and expression2. Such tables are called truth tables. Java evaluates to false or true all expressions that include relational operators, equality operators or logical operators.
expression1 |
expression2 |
expression1 && expression2 |
---|---|---|
false |
false |
false |
false |
true |
false |
TRue |
false |
false |
true |
true |
TRue |
Conditional OR (||) Operator
Now suppose that we wish to ensure that either or both of two conditions are true before we choose a certain path of execution. In this case, we use the || (conditional OR) operator, as in the following program segment:
if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 ) ) System.out.println ( "Student grade is A" );
This statement also contains two simple conditions. The condition semesterAverage >= 90 evaluates to determine whether the student deserves an A in the course because of a solid performance throughout the semester. The condition finalExam >= 90 evaluates to determine whether the student deserves an A in the course because of an outstanding performance on the final exam. The if statement then considers the combined condition
( semesterAverage >= 90 ) || ( finalExam >= 90 )
and awards the student an A if either or both of the simple conditions are true. The only time the message "Student grade is A" is not printed is when both of the simple conditions are false. Figure 5.15 is a truth table for operator conditional OR (||). Operator && has a higher precedence than operator ||. Both operators associate from left to right.
expression1 |
expression2 |
expression1 || expression2 |
---|---|---|
false |
false |
false |
false |
true |
true |
TRue |
false |
true |
true |
true |
TRue |
Short-Circuit Evaluation of Complex Conditions
The parts of an expression containing && or || operators are evaluated only until it is known whether the condition is true or false. Thus, evaluation of the expression
( gender == FEMALE ) && ( age >= 65 )
stops immediately if gender is not equal to FEMALE (i.e., the entire expression is false) and continues if gender is equal to FEMALE (i.e., the entire expression could still be TRue if the condition age >= 65 is true). This feature of conditional AND and conditional OR expressions is called short-circuit evaluation.
Common Programming Error 5.8
In expressions using operator &&, a conditionwe will call this the dependent conditionmay require another condition to be true for the evaluation of the dependent condition to be meaningful. In this case, the dependent condition should be placed after the other condition, or an error might occur. For example, in the expression ( i != 0 ) && ( 10 / i == 2 ), the second condition must appear after the first condition, or a divide-by-zero error might occur. |
Boolean Logical AND (&) and Boolean Logical OR (|) Operators
The boolean logical AND (&) and boolean logical inclusive OR (|) operators work identically to the && (conditional AND) and || (conditional OR) operators, with one exception: The boolean logical operators always evaluate both of their operands (i.e., they do not perform short-circuit evaluation). Therefore, the expression
( gender == 1 ) & ( age >= 65 )
evaluates age >= 65 regardless of whether gender is equal to 1. This is useful if the right operand of the boolean logical AND or boolean logical inclusive OR operator has a required side effecta modification of a variable's value. For example, the expression
( birthday == true ) | ( ++age >= 65 )
guarantees that the condition ++age >= 65 will be evaluated. Thus, the variable age is incremented in the preceding expression, regardless of whether the overall expression is true or false.
Error-Prevention Tip 5.4
For clarity, avoid expressions with side effects in conditions. The side effects may look clever, but they can make it harder to understand code and can lead to subtle logic errors. |
Boolean Logical Exclusive OR (^)
A simple condition containing the boolean logical exclusive OR (^) operator is true if and only if one of its operands is TRue and the other is false. If both operands are true or both are false, the entire condition is false. Figure 5.16 is a truth table for the boolean logical exclusive OR operator (^). This operator is also guaranteed to evaluate both of its operands.
expression1 |
expression2 |
expression1 ^ expression2 |
---|---|---|
false |
false |
false |
false |
true |
true |
true |
false |
TRue |
true |
true |
false |
Logical Negation (!) Operator
The ! (logical NOT, also called logical negation or logical complement) operator enables a programmer to "reverse" the meaning of a condition. Unlike the logical operators &&, ||, &, | and ^, which are binary operators that combine two conditions, the logical negation operator is a unary operator that has only a single condition as an operand. The logical negation operator is placed before a condition to choose a path of execution if the original condition (without the logical negation operator) is false, as in the program segment
if ( ! ( grade == sentinelValue ) ) System.out.printf( "The next grade is %d ", grade );
which executes the printf call only if grade is not equal to sentinelValue. The parentheses around the condition grade == sentinelValue are needed because the logical negation operator has a higher precedence than the equality operator.
In most cases, the programmer can avoid using logical negation by expressing the condition differently with an appropriate relational or equality operator. For example, the previous statement may also be written as follows:
if ( grade != sentinelValue ) System.out.printf( "The next grade is %d ", grade );
This flexibility can help a programmer express a condition in a more convenient manner. Figure 5.17 is a truth table for the logical negation operator.
expression |
!expression |
---|---|
false |
true |
TRue |
false |
Logical Operators Example
Figure 5.18 demonstrates the logical operators and boolean logical operators by producing their truth tables. The output shows the expression that was evaluated and the boolean result of that expression. The values of the boolean expressions are displayed with printf using the %b format specifier, which outputs the word "true" or the word "false" based on the expression's value. Lines 913 produce the truth table for &&. Lines 1620 produce the truth table for ||. Lines 2327 produce the truth table for &. Lines 3035 produce the truth table for |. Lines 3843 produce the truth table for ^. Lines 4647 produce the truth table for !.
Figure 5.18. Logical operators.
(This item is displayed on pages 206 - 207 in the print version)
1 // Fig. 5.18: LogicalOperators.java 2 // Logical operators. 3 4 public class LogicalOperators 5 { 6 public static void main( String args[] ) 7 { 8 // create truth table for && (conditional AND) operator 9 System.out.printf( "%s %s: %b %s: %b %s: %b %s: %b ", 10 "Conditional AND (&&)", "false && false", ( false && false ), 11 "false && true", ( false && true ), 12 "true && false", ( true && false ), 13 "true && true", ( true && true ) ); 14 15 // create truth table for || (conditional OR) operator 16 System.out.printf( "%s %s: %b %s: %b %s: %b %s: %b ", 17 "Conditional OR (||)", "false || false", ( false || false ), 18 "false || true", ( false || true ), 19 "true || false", ( true || false ), 20 "true || true", ( true || true ) ); 21 22 // create truth table for & (boolean logical AND) operator 23 System.out.printf( "%s %s: %b %s: %b %s: %b %s: %b ", 24 "Boolean logical AND (&)", "false & false", ( false & false ), 25 "false & true", ( false & true ), 26 "true & false", ( true & false ), 27 "true & true", ( true & true ) ); 28 29 // create truth table for | (boolean logical inclusive OR) operator 30 System.out.printf( "%s %s: %b %s: %b %s: %b %s: %b ", 31 "Boolean logical inclusive OR (|)", 32 "false | false", ( false | false ), 33 "false | true", ( false | true ), 34 "true | false", ( true | false ), 35 "true | true", ( true | true ) ); 36 37 // create truth table for ^ (boolean logical exclusive OR) operator 38 System.out.printf( "%s %s: %b %s: %b %s: %b %s: %b ", 39 "Boolean logical exclusive OR (^)", 40 "false ^ false", ( false ^ false ), 41 "false ^ true", ( false ^ true ), 42 "true ^ false", ( true ^ false ), 43 "true ^ true", ( true ^ true ) ); 44 45 // create truth table for ! (logical negation) operator 46 System.out.printf( "%s %s: %b %s: %b ", "Logical NOT (!)", 47 "!false", ( !false ), "!true", ( !true ) ); 48 } // end main 49 } // end class LogicalOperators
|
Figure 5.19 shows the precedence and associativity of the Java operators introduced so far. The operators are shown from top to bottom in decreasing order of precedence.
Operators |
Associativity |
Type |
---|---|---|
++ -- |
right to left |
unary postfix |
++ - + - ! (type) |
right to left |
unary prefix |
* / % |
left to right |
multiplicative |
+ - |
left to right |
additive |
< <= > >= |
left to right |
relational |
== != |
left to right |
equality |
& |
left to right |
boolean logical AND |
^ |
left to right |
boolean logical exclusive OR |
| |
left to right |
boolean logical inclusive OR |
&& |
left to right |
conditional AND |
|| |
left to right |
conditional OR |
?: |
right to left |
conditional |
= += -= *= /= %= |
right to left |
assignment |
Introduction to Computers, the Internet and the World Wide Web
Introduction to Java Applications
Introduction to Classes and Objects
Control Statements: Part I
Control Statements: Part 2
Methods: A Deeper Look
Arrays
Classes and Objects: A Deeper Look
Object-Oriented Programming: Inheritance
Object-Oriented Programming: Polymorphism
GUI Components: Part 1
Graphics and Java 2D™
Exception Handling
Files and Streams
Recursion
Searching and Sorting
Data Structures
Generics
Collections
Introduction to Java Applets
Multimedia: Applets and Applications
GUI Components: Part 2
Multithreading
Networking
Accessing Databases with JDBC
Servlets
JavaServer Pages (JSP)
Formatted Output
Strings, Characters and Regular Expressions
Appendix A. Operator Precedence Chart
Appendix B. ASCII Character Set
Appendix C. Keywords and Reserved Words
Appendix D. Primitive Types
Appendix E. (On CD) Number Systems
Appendix F. (On CD) Unicode®
Appendix G. Using the Java API Documentation
Appendix H. (On CD) Creating Documentation with javadoc
Appendix I. (On CD) Bit Manipulation
Appendix J. (On CD) ATM Case Study Code
Appendix K. (On CD) Labeled break and continue Statements
Appendix L. (On CD) UML 2: Additional Diagram Types
Appendix M. (On CD) Design Patterns
Appendix N. Using the Debugger
Inside Back Cover