Boolean Logical Compound Assignment Operators: &=, ^=, |= – Basic Elements, Primitive Data Types, and Operators

Boolean Logical Compound Assignment Operators: &=, ^=, |=

Compound assignment operators for the boolean logical operators are defined in Table 2.27. The left-hand operand must be a boolean variable, and the right-hand operand must be a boolean expression. An identity conversion is applied implicitly on assignment. These operators can also be applied to integral operands to perform bitwise compound assignments (p. 82). See also the discussion on arithmetic compound assignment operators (p. 66).

Table 2.27 Boolean Logical Compound Assignment Operators

ExpressionGiven a and b are of type boolean or Boolean, the expression is evaluated as:
b &= ab = (b & (a))
b ^= ab = (b ^ (a))
b |= ab = (b | (a))

Here are some examples to illustrate the behavior of boolean logical compound assignment operators:

Click here to view code image

boolean b1 = false, b2 = true, b3 = false;
Boolean b4 = false;
b1 |= true;             // true
b4 ^= b1;               // (1) true, unboxing in (b4 ^ (b1)), boxing on assignment
b3 &= b1 | b2;          // (2) false, b3 = (b3 & (b1 | b2))
b3 = b3 & b1 | b2;      // (3) true,  b3 = ((b3 & b1) | b2)

The assignment at (1) entails unboxing to evaluate the expression on the right-hand side, followed by boxing to assign the boolean result. It is also instructive to compare how the assignments at (2) and (3) are performed, as they lead to different results with the same values of the operands, showing how the precedence affects the evaluation.

2.15 Conditional Operators: &&, ||

The conditional operators && and || are similar to their counterpart logical operators & and |, except that their evaluation is short-circuited. Given that x and y represent values of boolean or Boolean expressions, the conditional operators are defined in Table 2.28. In the table, the operators are listed in decreasing order of precedence.

Table 2.28 Conditional Operators

Conditional ANDx && ytrue if both operands are true; otherwise false.
Conditional ORx || ytrue if either or both operands are true; otherwise false.

Unlike their logical counterparts & and |, which can also be applied to integral operands for bitwise operations, the conditional operators && and || can be applied to only boolean operands. Their evaluation results in a boolean value. Truth values for conditional operators are shown in Table 2.29. Not surprisingly, the conditional operators have the same truth values as their counterpart logical operators. However, unlike with their logical counterparts, there are no compound assignment operators for the conditional operators.

Table 2.29 Truth Values for Conditional Operators

xyAND
x && y
OR
x || y
truetruetruetrue
truefalsefalsetrue
falsetruefalsetrue
falsefalsefalsefalse