### 2.14 Boolean Logical Operators: !, ^, &, |

Boolean logical operators include the unary operator ! (logical complement) and the binary operators & (logical AND), | (logical inclusive OR), and ^ (logical exclusive OR, also called logical XOR). These operators can be applied to boolean or Boolean operands, returning a boolean value. The operators &, |, and ^ can also be applied to integral operands to perform bitwise logical operations (p. 82).

Given that x and y represent boolean expressions, the boolean logical operators are defined in Table 2.26. The precedence of the operators decreases from left to right in the table.

Table 2.26 Truth Values for Boolean Logical Operators

x | y | Complement !x | AND x & y | XOR x ^ y | OR x | y |

true | true | false | true | false | true |

true | false | false | false | true | true |

false | true | true | false | true | true |

false | false | true | false | false | false |

These operators always evaluate both of the operands, unlike their counterpart conditional operators && and || (p. 80). Unboxing is applied to the operand values, if necessary. Truth values for boolean logical operators are shown in Table 2.26, where x and y are either of type boolean or Boolean.

#### Operand Evaluation for Boolean Logical Operators

In the evaluation of boolean expressions involving boolean logical AND, XOR, and OR operators, both the operands are evaluated. The order of operand evaluation is always from left to right.

if (i > 0 & i++ < 10) {/*…*/} // i will be incremented, regardless of value in i.

The binary boolean logical operators have lower precedence than the arithmetic and relational operators, but higher precedence than the assignment, conditional AND, and OR operators (p. 80). This is illustrated in the following examples:

boolean b1, b2, b3 = false, b4 = false;

Boolean b5 = true;

b1 = 4 == 2 & 1 < 4; // false, evaluated as (b1 = ((4 == 2) & (1 < 4)))

b2 = b1 | !(2.5 >= 8); // true

b3 = b3 ^ b5; // true, unboxing conversion on b5

b4 = b4 | b1 & b2; // false

Here, the order of evaluation is illustrated for the last expression statement:

(b4 = (b4 | (b1 & b2)))

⇒ (b4 = (false | (b1 & b2)))

⇒ (b4 = (false | (false & b2)))

⇒ (b4 = (false | (false & true)))

⇒ (b4 = (false | false))

⇒ (b4 = false)

⇒ false

Note that b2 was evaluated, although strictly speaking, it was not necessary. This behavior is guaranteed for boolean logical operators.