Comprehensive Operators & Short-Circuit Evaluation
1Concept
Java short-circuit logical operators (&&, ||) evaluate the right-hand operand ONLY if the left operand does not determine the final truth value. This prevents NullPointerExceptions during chain checks.
2Architecture Diagram
Operand 1 (false) && Operand 2 (skipped!) ---> Result: false Operand 1 (true) || Operand 2 (skipped!) ---> Result: true
3Code Example
Core Java
public class ShortCircuitDemo {
public static void main(String[] args) {
String text = null;
if (text != null && text.length() > 0) {
System.out.println(text);
} else {
System.out.println("Safe check: text is null, length check skipped!");
}
}
}4Expected Output
Safe check: text is null, length check skipped!
5Key Takeaways
- ✓&& and || short-circuit; single & and | do NOT short-circuit.
- ✓Ternary operator requires matching return types or auto-boxing.
- ✓Assigning inside boolean conditions (if (b = true)) is a common bug.