AP® Computer Science A · Unit 2 · Topic 2.5

Short-Circuit Evaluation

Short-circuit evaluation means Java stops checking a compound condition as soon as the answer is already decided: && quits on a false, || quits on a true, and the other side never runs.

Java evaluates conditions left to right, and it stops early whenever it already knows the answer. For &&, both sides must be true, so the moment the left side is false, the whole expression is false no matter what the right side says. Java skips the right side entirely. For ||, only one side needs to be true, so the moment the left side is true, Java skips the right side too, since the result is already decided.

This is not just an efficiency trick. The skipped operand never runs at all, which means any side effect inside it, a method call, an increment, an array access, simply does not happen. That matters most when the right side depends on the left side being safe to evaluate. Checking arr ≠ null before arr.length > 0 works because a false first check blocks Java from ever touching arr.length. Reverse the order and Java checks arr.length first, which throws an exception immediately if arr is null, before the null check ever gets a chance to help.

This connects directly to trace tables and loop conditions covered nearby: a loop guard like i < n && someCall() can silently skip someCall() forever once i < n goes false, which explains loops that seem to stop updating a variable partway through. Reading conditions as a left-to-right gate, not a pair of independent checks, is the same skill used to trace boolean expressions and predict exactly which branches and side effects execute.

Key terms

Short-circuit evaluation
Stopping evaluation of a compound boolean expression as soon as the overall result is already determined.
&& (logical AND)
True only if both operands are true; stops checking as soon as the left operand is false.
|| (logical OR)
True if either operand is true; stops checking as soon as the left operand is true.
Side effect
A change a piece of code causes beyond producing a value, such as incrementing a variable or throwing an exception.

Watch it explained

  1. How it worksHow does AND bail out as soon as the left side is false, and OR as soon as it is true?
  2. Worked exampleTrace why arr ≠ null && arr.length > 0 is safe but the reversed order crashes.
  3. Worked exampleFind what happens to count in i < n && count++ > 0 when i is not less than n.
  4. Common mistakeWhy isn't the order of two conditions joined by AND merely a matter of style?

Check yourself

Your turn1 of 2
arr ≠ null && arr.length > 0 is safe when arr is null, but arr.length > 0 && arr ≠ null (reversed order) crashes. Why?

End of topic.