Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Operators

Java logical operators

Reference for Java logical operators &&, ||, ! and the non-short-circuit &, | and ^ on booleans: short-circuit evaluation and common mistakes.

The logical operators combine boolean values. && (conditional AND) is true when both operands are true. || (conditional OR) is true when at least one is true. ! negates a single operand. All three work only on boolean; Java has no "truthy" values.

&& and || short-circuit: the right operand is evaluated only if the left one does not already decide the result. That makes s != null && s.length() > 0 safe. The single-character forms &, | and ^ also accept booleans but always evaluate both sides.

Java
if (user != null && user.isActive()) { ... }

Try it

Java Short-circuit evaluation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Truth tables and xor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
a && b     // conditional AND, short-circuits
a || b     // conditional OR, short-circuits
!a         // NOT
a & b   a | b   a ^ b    // non-short-circuit AND, OR, XOR on booleans
Operator Result
a && b true if both are true; b is skipped when a is false
a || b true if either is true; b is skipped when a is true
!a the opposite of a
a ^ b true if exactly one is true

Usage notes

  • Precedence: ! binds tightest, then &, ^, |, then &&, then ||. So a || b && c means a || (b && c). Add parentheses when mixing them.
  • Side effects in the right operand may not happen. Do not put required work (a method call that must run) behind && or ||.
  • De Morgan's laws: !(a && b) equals !a || !b, and !(a || b) equals !a && !b. Useful for simplifying conditions.
  • & and | on integers are bitwise, not logical; see Bitwise operators. Mixing an int with a boolean does not compile.
  • Use ^ or != to express "exactly one of two". For boolean, a ^ b is the same as a != b.
  • Boxed Boolean is unboxed first; a null throws NullPointerException.
  • No &&= or ||=. Use x = x && y or the non-short-circuit x &= y.