# Logical Operators

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.

Figure 5.14. && (conditional AND) operator truth table.

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.

Figure 5.15. || (conditional OR) operator truth table.

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.

Figure 5.16. ^ (boolean logical exclusive OR) operator truth table.

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
```

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
```

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.

Figure 5.17. ! (logical negation, or logical NOT) operator truth table.

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
```

 ```Conditional AND (&&) false && false: false false && true: false true && false: false true && true: true Conditional OR (||) false || false: false false || true: true true || false: true true || true: true Boolean logical AND (&) false & false: false false & true: false true & false: false true & true: true Boolean logical inclusive OR (|) false | false: false false | true: true true | false: true true | true: true Boolean logical exclusive OR (^) false ^ false: false false ^ true: true true ^ false: true true ^ true: false Logical NOT (!) !false: true !true: false ```

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.

Figure 5.19. Precedence/associativity of the operators discussed so far.

(This item is displayed on pages 207 - 208 in the print version)

Operators

Associativity

Type

++ --

right to left

unary postfix

++ - + - ! (type)

right to left

unary prefix

* / %

left to right

multiplicative

+ -

left to right

< <= > >=

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

Java How to Program (6th Edition) (How to Program (Deitel))
ISBN: 0131483986
EAN: 2147483647
Year: 2003
Pages: 615