Card 05/ 09

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.

java
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.

When each operator stops early
OperatorStops when the left side isBecause
&&falseNothing on the right can make it true
||trueNothing on the right can make it false
&NeverBoth sides are always evaluated
|NeverBoth 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.