Sub topic 10
Short-Circuit Evaluation
Java can sometimes work out the result of a logical expression without checking every part. It then skips the parts it does not need. This is called short-circuit evaluation.
Short-circuiting matters for two reasons. It can prevent an error, such as trying to use a missing value. It can also skip an action you expected to happen.
This chapter assumes you know how to declare Java variables and run a simple Java program.
How Java decides what to check
An expression is a piece of code that produces a value. A boolean value is either true or false. The values or expressions on either side of an operator are its operands.
Java checks the left operand of && or || first. It checks the right operand only if it needs that value to decide the result.
| Operator | Left operand | Is the right operand checked? | Result | Column | Column |
|---|---|---|---|---|---|
| `&&` | `false` | No | `false` | ||
| `&&` | `true` | Yes | The right operand’s value | ||
| ` | ` | `true` | No | `true` | |
| ` | ` | `false` | Yes | The right operand’s value |
For &&, both operands must be true for the result to be true. If the left operand is false, Java already knows the result is false.
For ||, either operand can make the result true. If the left operand is true, Java already knows the result is true.
Watch operands get skipped
A method is a named set of instructions. The program below uses a method named check. When called, it prints a message and returns the boolean value it was given.
Save the program as ShortCircuitDemo.java, then compile and run it as you would any Java program.
public class ShortCircuitDemo {
static boolean check(String label, boolean value) {
System.out.println("checked " + label);
return value;
}
public static void main(String[] args) {
System.out.println("A: " + (false && check("A", true)));
System.out.println("B: " + (true && check("B", false)));
System.out.println("C: " + (true || check("C", false)));
System.out.println("D: " + (false || check("D", true)));
String name = null;
boolean hasText = name != null && !name.isEmpty();
boolean missingOrEmpty = name == null || name.isEmpty();
System.out.println("has text: " + hasText);
System.out.println("missing or empty: " + missingOrEmpty);
int divisor = 0;
boolean resultAboveOne = divisor != 0 && 10 / divisor > 1;
System.out.println("division result above 1: " + resultAboveOne);
}
}The output is:
A: false
checked B
B: false
C: true
checked D
D: true
has text: false
missing or empty: true
division result above 1: falseLook at the first four results:
- In A, the left side of
&&is false. Java skipscheck, so there is nochecked Amessage. - In B, the left side of
&&is true. Java callscheckto find the result. - In C, the left side of
||is true. Java skipscheck, so there is nochecked Cmessage. - In D, the left side of
||is false. Java callscheckto find the result.
The missing messages show that Java does not merely ignore the returned values. It skips the method calls themselves.
Use a guard to prevent an error
A guard is a check placed before an operation that may not be safe. Short-circuiting lets the guard stop Java from performing that operation.
In the program, name is a String, a value used to hold text. The value null means that name does not refer to a string. The method isEmpty() checks whether a string has no characters. Calling it on null would cause an error called a NullPointerException.
The hasText expression avoids that error:
- Java checks
name != null. This asks whethernameis not null. - Because
nameis null, the check is false. - The operator is
&&, so Java skips!name.isEmpty(). - The result is false.
The ! operator means “not.” When name is a string, !name.isEmpty() is true if that string is not empty.
The missingOrEmpty expression uses || instead:
- Java checks
name == null. This asks whethernameis null. - The check is true.
- The operator is
||, so Java skipsname.isEmpty(). - The result is true.
If name referred to a string, each expression would need to check isEmpty() to find its result.
Put the guard first
Short-circuiting only skips work to the right of the operator. It cannot protect an operation that Java has already tried.
For example, name.isEmpty() || name == null is not a safe null check. Java tries name.isEmpty() first. If name is null, the error happens before Java reaches the check on the right.
The division example follows the same pattern. It checks divisor != 0 before dividing by divisor. Because the divisor is zero, Java skips the division. Without that guard, integer division by zero would cause an error called an ArithmeticException.
Notice that resultAboveOne answers a specific question: whether the divisor is nonzero and the division result is greater than one. A false result does not always mean division is impossible; it can also mean the result was not greater than one.
Skipping a call also skips its effects
A side effect is a change or action caused by an expression besides producing its value. Printing a message is a side effect. Changing a variable or saving information can also be a side effect.
In the example, the check method prints when it runs. Since Java skips the calls in A and C, it skips their print actions too.
Keep this in mind when putting a method call on the right of && or ||. Ask two questions:
- Might Java skip this call?
- If it does, is it safe to skip everything the call does?
If the action must happen every time, perform it before the logical expression rather than relying on an operand that may be skipped.
Follow longer expressions one step at a time
A longer expression can skip one part but still evaluate another. Consider (first && second) || third, where each name stands for a boolean expression.
If first is false, Java skips second: the result inside the parentheses must be false. But Java still needs to evaluate third, because third could make the full || expression true.
If first and second are both true, the result inside the parentheses is true. Java then skips third, because the full || expression is already true.
To trace an expression, start on the left. At each && or ||, decide whether the value so far makes the next operand unnecessary. Parentheses show which parts belong together, but they do not make Java run an operand that short-circuiting skips.
Avoid a similar-looking mistake
For boolean operands, Java also accepts the single-character operators & and |. Unlike && and ||, they do not short-circuit: they evaluate both operands. Do not replace && with & in a guard that must skip an unsafe operation.
Exercise
If ready is false, does Java call check("work", true) in ready && check("work", true)? What is the result?
Show answer
No. The left operand is false, so Java skips the call. The result is false.
Exercise
For a nullable string named name, why is name == null || name.isEmpty() safe when name is null?
Show answer
The left operand is true, so || skips name.isEmpty(). Java does not call the method on null.
Exercise
In (first && second) || third, first is false. Which of the other expressions does Java evaluate?
Show answer
Java skips second because the && result is already false. It evaluates third because it still needs to decide the result of ||.