Card 05/ 09
All 9 cards
ConceptDifficulty: Intermediate1 min
Short-Circuiting, and the Null Check That Leans On It
A condition that reads like it does two things and sometimes only does one. It is the reason a null check works at all.
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 — 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 |
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.