Sub topic 17
Logical operators and short-circuiting
This chapter covers the Apex logical operators &&, ||, and !. It explains how short-circuit evaluation works and where it fails. It assumes you know Boolean values, if statements, and how null behaves in Apex (see the earlier chapters on null and comparison).
The three logical operators
Apex has three logical operators. Each works on Boolean values.
| Operator | Name | Result | Column | Column |
|---|---|---|---|---|
| `&&` | AND | `true` only if both operands are `true` | ||
| `\ | \ | ` | OR | `true` if at least one operand is `true` |
| `!` | NOT | The opposite of the operand |
The truth tables are the standard ones.
| a | b | a && b | a \ | \ | b |
|---|---|---|---|---|---|
| true | true | true | true | ||
| true | false | false | true | ||
| false | true | false | true | ||
| false | false | false | false |
Boolean isActive = true;
Boolean hasOpenCases = false;
System.debug(isActive && hasOpenCases); // false
System.debug(isActive || hasOpenCases); // true
System.debug(!isActive); // falseApex has no ^^ logical XOR operator. The ^ operator exists, but it is a bitwise operator (see the bitwise chapter). To test "exactly one is true" on Booleans, compare them with !=:
Boolean a = true;
Boolean b = false;
System.debug(a != b); // true: exactly one of a and b is trueOperands must be Boolean
Apex does not treat numbers, strings, or collections as true or false. A condition such as if (count) does not compile when count is an Integer. You must write a comparison:
Integer count = 3;
if (count > 0) {
System.debug('has items');
}Short-circuit evaluation
Apex evaluates && and || from left to right and stops as soon as the result is known.
- For
a && b, ifaisfalse, the result isfalse. Apex does not evaluateb. - For
a || b, ifaistrue, the result istrue. Apex does not evaluateb.
The main use is guarding a risky expression. Put the safety check on the left and the risky call on the right.
Boolean hasValue = false;
List<Integer> items = null;
if (items != null && !items.isEmpty()) {
hasValue = true;
}
System.debug(hasValue);Because items != null is false, items.isEmpty() never runs. If you reversed the order, calling isEmpty() on a null list would throw a System.NullPointerException.
The same pattern works with ||. Here the left side catches the null case and lets the code skip the right side:
String name = null;
Boolean isMissing = name == null || name.length() == 0;
System.debug(isMissing); // trueSeeing the skip happen
A method with a side effect shows whether the right operand ran.
public class ShortCircuitDemo {
public static Boolean check(String label, Boolean result) {
System.debug('Evaluating ' + label);
return result;
}
public static void run() {
Boolean r1 = check('A', false) && check('B', true);
System.debug('r1 = ' + r1);
Boolean r2 = check('C', true) || check('D', false);
System.debug('r2 = ' + r2);
}
}Running ShortCircuitDemo.run(); in anonymous Apex logs Evaluating A, r1 = false, Evaluating C, and r2 = true. Methods B and D never run.
Gotchas
Side effects in the right operand
Do not put required work in the right operand of && or ||. If the left side decides the result, the work is skipped. This is a common source of bugs when a method both checks something and changes state, such as incrementing a counter or adding to a list. Call such methods in their own statement, then combine the Boolean results.
Boolean first = check('A', false);
Boolean second = check('B', true);
Boolean both = first && second; // both checks always runNull Boolean values
A Boolean variable can be null. Using a null Boolean in &&, ||, !, or an if condition throws a System.NullPointerException.
Boolean flag; // null, not false
// if (flag) { } // would throw NullPointerException
if (flag == true) {
System.debug('set and true');
} else {
System.debug('false or null');
}Comparing with == true is safe because null == true evaluates to false. Note that flag == false is also false when flag is null. A null Boolean is neither true nor false. Boolean SObject fields that are checkboxes are never null, but a Boolean variable you declare without a value is.
Mixing && and || without parentheses
&& has higher precedence than ||, so a || b && c means a || (b && c). Add parentheses when the intent is not obvious. The precedence chapter covers the full ordering.
Boolean a = true;
Boolean b = false;
Boolean c = false;
System.debug(a || b && c); // true: a || (b && c)
System.debug((a || b) && c); // falseThe non-short-circuit forms don't exist
Some languages offer & and | as non-short-circuit Boolean operators. In Apex, & and | are bitwise operators for integer types. They are not a substitute for && and ||. If you need both sides evaluated, store each result in a variable first, as shown above.
De Morgan's laws
The ! operator can be pushed through a condition. These pairs are equivalent:
!(a && b)is the same as!a || !b!(a || b)is the same as!a && !b
Use these to simplify negated conditions that are hard to read.
Boolean isClosed = false;
Boolean isArchived = true;
System.debug(!(isClosed || isArchived)); // false
System.debug(!isClosed && !isArchived); // falseCombining with null-safe operators
Short-circuiting is one way to avoid null errors. The safe navigation operator ?. and the null coalescing operator ?? cover similar cases with less code. Compare these:
Account acc = null;
Boolean longName1 = acc != null && acc.Name != null && acc.Name.length() > 10;
Boolean longName2 = (acc?.Name?.length() ?? 0) > 10;
System.debug(longName1); // false
System.debug(longName2); // falseBoth avoid a null reference error. The && form states each check explicitly. The ?. form is shorter but harder to read when the chain grows.
Summary of rules
&&,||, and!accept onlyBooleanoperands.&&skips the right side when the left side isfalse.||skips the right side when the left side istrue.- A null
Booleanthrows aNullPointerExceptionin a logical expression. Compare with== trueif the value may be null. &&binds tighter than||. Use parentheses for clarity.
Exercise
Given List<Integer> items = null;, which of these two conditions throws a NullPointerException, and why? (1) items != null && items.size() > 0 (2) items.size() > 0 && items != null
Show answer
Condition 2 throws. It evaluates items.size() first, and calling a method on a null list fails. In condition 1, items != null is false, so && short-circuits and items.size() never runs.
Exercise
Given Boolean flag; (never assigned), what do flag == true and flag == false evaluate to, and what happens with if (flag)?
Show answer
Both comparisons evaluate to false, because the variable is null and a null Boolean is neither true nor false. if (flag) throws a System.NullPointerException.
Exercise
What does true || false && false evaluate to, and why?
Show answer
It evaluates to true. && has higher precedence than ||, so the expression is true || (false && false), which is true || false. The short-circuit rule means the right side is not evaluated at all once the left side is true.