Unit 2 Cycle 1 Day 8: Short-Circuit Evaluation
Share
Short-Circuit Evaluation
Section 2.5 — Compound Boolean
Key Concept
Short-circuit evaluation means Java stops evaluating a boolean expression as soon as the result is determined. With &&, if the left operand is false, the right operand is never evaluated (because the result must be false). With ||, if the left operand is true, the right is skipped. This matters when the right operand has side effects or could cause an error. The pattern str != null && str.length() > 0 relies on short-circuit evaluation to avoid a NullPointerException.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) no
x != 0 is false. With &&, Java short-circuits: since the left side is false, the right side (10 / x) is never evaluated. No division by zero occurs. The else branch prints "no".
Why Not the Others?
(A) The first condition is false, so the AND expression is false regardless of the second condition.
(C) Short-circuit evaluation prevents 10 / x from being evaluated when x != 0 is false.
(D) The code is syntactically valid and compiles fine.
Common Mistake
Short-circuit evaluation is a safety mechanism. With &&, if the left side is false, the right side is skipped entirely. This prevents errors like division by zero or null pointer exceptions.
AP Exam Tip
Short-circuit evaluation is heavily tested on the AP exam. && skips the right side if left is false. || skips the right side if left is true.