Logical Operators in Java — <code>&&</code>, <code>||</code>, <code>!</code>
Java has three logical operators on booleans: && (AND), || (OR), ! (NOT). The binary ones are short-circuit — they don't evaluate the right-hand side if the result is already determined by the left-hand side.
Truth table
| a | b | a && b | a || b | !a |
|---|---|---|---|---|
| true | true | true | true | false |
| true | false | false | true | false |
| false | true | false | true | true |
| false | false | false | false | true |
Short-circuit is load-bearing
if (s != null && s.length() > 0) { ... } // ✅ length() never called when s is null
if (s.length() > 0 && s != null) { ... } // ❌ NPE first
Same for ||:
if (s == null || s.isEmpty()) { ... } // ✅ isEmpty never called on null
Non-short-circuit & and |
if (check1() & check2()) { ... } // both called, always
if (validate() | audit()) { ... } // call audit() even if validate() is true
Use these only when the right-hand side has a side effect you want to guarantee.
! — negation
if (!list.isEmpty()) { ... }
if (!(a || b)) { ... } // De Morgan: same as !a && !b
De Morgan's laws
!(a && b) == !a || !b
!(a || b) == !a && !b
Useful for rewriting conditions without double negatives.
XOR — ^
^ is exclusive-or: true if exactly one operand is true. Not short-circuit, not a common need:
boolean exactlyOne = hasA ^ hasB;
Common mistakes
- Using
&when you meant&&— loses short-circuit and can hit NPE. - Redundant
== true—if (active == true)is justif (active). - Assignment instead of equality —
if (done = true)assigns. Use==. - Boxing in conditions —
Boolean b = null; if (b)throws NPE on unboxing.
Related
Pillar: Java operators. See also boolean, if/else.