Card 05/ 09
Short-Circuit Evaluation with && and ||
Why name != null && name.length() > 3 never crashes, and the reversed version does.
&& and || short-circuit: they evaluate the left side first, and skip the right side when the left already decides the answer. That is what lets a null check on the left protect a method call on the right.
A condition that reads as if it does two things, and sometimes only does one:
if (name != null && name.length() > 3) {
System.out.println("long enough");
}If name is null, the left side is false. && can already answer the whole question, since false and anything is false, so it never evaluates the right side, and name.length() is never called on nothing.
| Operator | Stops when the left side is | Because |
|---|---|---|
&& | false | Nothing on the right can make it true |
|| | true | Nothing on the right can make it false |
& | Never | Both sides are always evaluated |
| | Never | Both sides are always evaluated |
The single & and | exist for the rare case where the right side must run anyway, such as a method with a side effect you need. In a condition, you almost always want the doubled form.
Short-circuiting means the order of your conditions is part of their meaning. Put the cheap test and the guard on the left, and the expensive or unsafe one on the right.
← → move through sections and cards