Unit 2 Cycle 2 Day 5: Short-Circuit with Side Effects
Share
Short-Circuit with Side Effects
Section 2.5 — Compound Boolean
Key Concept
Short-circuit evaluation becomes especially important when the second operand has side effects such as incrementing a variable, calling a method, or modifying an object. If the first operand of && is false, the side effect in the second operand never occurs. The AP exam creates scenarios where the final state of variables depends on whether short-circuit evaluation skipped the second operand. Always evaluate the first operand completely before deciding whether the second operand executes.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) 5 10
a > 3 is true. Since the left side of || is true, Java short-circuits and does NOT evaluate ++b. b remains 10. Prints 5 10.
Why Not the Others?
(A) ++b is never executed due to short-circuit evaluation, so b stays at 10.
(C) a is never modified. The expression only reads a, it does not increment it.
(D) Neither a nor b is modified. Short-circuit skips the right side entirely.
Common Mistake
Short-circuit evaluation means ++b is never executed when the left side of || is already true. This is why side effects (like ++) inside boolean expressions are dangerous and hard to predict.
AP Exam Tip
On the AP exam, short-circuit questions with side effects (++ or method calls) test whether the right side is evaluated. With ||: skip right if left is true. With &&: skip right if left is false.