Card 05/ 09

ConceptDifficulty: Intermediate1 min

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:

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, since 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

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.