Logical Operators in Java — <code>&amp;&amp;</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

aba && ba || b!a
truetruetruetruefalse
truefalsefalsetruefalse
falsetruefalsetruetrue
falsefalsefalsefalsetrue

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 == trueif (active == true) is just if (active).
  • Assignment instead of equalityif (done = true) assigns. Use ==.
  • Boxing in conditionsBoolean b = null; if (b) throws NPE on unboxing.

Related

Pillar: Java operators. See also boolean, if/else.