Short-Circuit Evaluation

Part of: Boolean Expressions & if Statements

Lazy Evaluation Java's && and use short-circuit evaluation : they stop as soon as the result is determined and skip evaluating the rest of the expression. This is both a performance feature and a safety tool. How && Short-Circuits For a && b, if a is false, the whole expression is already false no matter what b is, so b is never evaluated : When x is 0, the left side x != 0 is false, so Java never computes 10 / x. This avoids a divide-by-zero crash. Reorder the operands and you would get an ArithmeticException. How Short-Circuits For a b, if a is true, the whole expression is already true, so b is never evaluated : Because s == null is true, Java skips s.length() and avoids a NullPointerException. The order is what protects you. Why Order Matters The guard condition must come first: - &&: put the cheap/safe check that can rule things out on the left . - : put the check that can confirm things early on the left . Observable Side Effects Short-circuiting changes whether side-effecting operands run. If the right operand calls a method that prints or modifies state, it may be skipped: For the AP exam, you must be able to trace exactly which operands get evaluated. Remember: false && X

Challenge: Safe Average Check