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[].
boolean ready = true; boolean adult = age >= 18;
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
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), notif (done == true); andif (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()returnstrueonly for the text "true" in any case, andfalsefor everything else, includingnull. It never throws. - Boxed
Booleancan benull, and unboxing anullthrowsNullPointerException. Prefer the primitive for flags. - Naming. Name booleans like questions:
isEmpty,hasNext,enabled. - Many flags? Consider an
enum,EnumSetorBitSetinstead of a pile of boolean parameters, which make call sites unreadable. - A
switchcannot take a boolean selector.