How does Java's short-circuit evaluation for && and || operators differ from the non-short-circuiting & and | operators when applied to boolean operands, and why does this distinction matter for avoiding NullPointerException?
Short answer
&& and || short-circuit: for &&, if the left operand is false, the right operand is NEVER evaluated at all (since the overall result is already determined to be false); for ||, if the left operand is true, the right operand is never evaluated -- & and | (when applied to boolean…
Advertisement
AModel answer
&& and || short-circuit: for &&, if the left operand is false, the right operand is NEVER evaluated at all (since the overall result is already determined to be false); for ||, if the left operand is true, the right operand is never evaluated -- & and | (when applied to boolean operands, distinct from their bitwise usage on integer types) always evaluate BOTH operands regardless, which matters significantly when the right operand has a side effect or could throw an exception (like a method call that would throw NullPointerException on a null reference), since short-circuiting lets you safely guard against that condition in the left operand first.
String value = null;
// Safe: short-circuit && never evaluates the right side if the left is false
if (value != null && value.length() > 0) {
System.out.println("Has content");
}
// DANGEROUS: non-short-circuiting & always evaluates BOTH sides
// if (value != null & value.length() > 0) { } // throws NullPointerException when value is null!Real-world example
A null-safety guard clause relies specifically on && short-circuit evaluation to check value != null before calling value.length() in the same condition, a pattern that would throw a NullPointerException immediately if the non-short-circuiting & operator were mistakenly used instead.
Likely follow-ups
- Are there any legitimate, intentional use cases for the non-short-circuiting & and | operators on boolean operands, given the risk they introduce?
- How does this short-circuit behavior interact with side-effecting method calls used specifically for their side effect within a condition?
Related topics