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.
if (user != null && user.isActive()) { ... }
Try it
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.
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
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||. Soa || b && cmeansa || (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 anintwith abooleandoes not compile.- Use
^or!=to express "exactly one of two". Forboolean,a ^ bis the same asa != b. - Boxed
Booleanis unboxed first; anullthrowsNullPointerException. - No
&&=or||=. Usex = x && yor the non-short-circuitx &= y.