Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Types and Literals

The boolean type

Reference for Java boolean: the true/false type, logical and comparison operators, short-circuit evaluation, Boolean parsing and common mistakes.

boolean has exactly two values, true and false. It is the type of every comparison and of every condition in if, while, for and the ternary operator. Unlike C, Java does not treat numbers, strings or null as truthy or falsy: if (count) does not compile, you must write if (count != 0).

A boolean cannot be cast to or from an integer. The size of a boolean is not defined by the language; the JVM typically uses one byte for a field and one byte per element in a boolean[].

Java
boolean ready = true;
boolean adult = age >= 18;

Try it

Java Conditions and short-circuiting

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 Parsing and the Boolean class

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
boolean name = true;
boolean name = expression;
Operator Meaning
!a logical NOT
a && b AND, short-circuit
a || b OR, short-circuit
a & b, a | b, a ^ b AND, OR, XOR without short-circuit
a == b, a != b equality

Default value (fields and array elements): false. Wrapper class: java.lang.Boolean.

Usage notes

  • Do not compare to a literal. Write if (done), not if (done == true); and if (flag = true) is an assignment that compiles for booleans and is always true.
  • Short-circuiting makes guards such as s != null && s.isEmpty() safe. Use & and | only when you need both sides evaluated.
  • Parsing is lenient. Boolean.parseBoolean() returns true only for the text "true" in any case, and false for everything else, including null. It never throws.
  • Boxed Boolean can be null, and unboxing a null throws NullPointerException. Prefer the primitive for flags.
  • Naming. Name booleans like questions: isEmpty, hasNext, enabled.
  • Many flags? Consider an enum, EnumSet or BitSet instead of a pile of boolean parameters, which make call sites unreadable.
  • A switch cannot take a boolean selector.