The <code>boolean</code> Primitive in Java β true and false
boolean holds exactly one of two values: true or false. Unlike C or JavaScript, Java has no notion of "truthy" β if (count) or if (name) won't compile.
Declaration
boolean active = true;
boolean hasError = false;
boolean done; // default (fields only) = false
Where boolean appears
- Conditions in
if,while,for, ternary?:. - Return type of predicate methods:
isEmpty(),contains(),matches(). - Flag fields:
private boolean dirty;
Operators
boolean ok = a && b; // short-circuit AND
boolean any = a || b; // short-circuit OR
boolean not = !a; // NOT
boolean both = a & b; // non-short-circuit AND (always evaluates both)
boolean xor = a ^ b; // XOR
Short-circuit matters when the right-hand side has a side effect or might throw:
if (s != null && s.length() > 0) { ... } // β
length() never called on null
if (s.length() > 0 && s != null) { ... } // β NullPointerException first
Naming conventions
boolean isActive; // state
boolean hasChildren; // ownership / possession
boolean canEdit; // capability / permission
boolean shouldRetry; // policy / intent
Avoid negated names: prefer isEnabled over isNotDisabled β double negatives are hard to read.
Boolean wrapper pitfall
Boolean maybe = null;
if (maybe) { ... } // β NullPointerException on unboxing
if (Boolean.TRUE.equals(maybe)) { ... } // β
null-safe
Parsing
Boolean.parseBoolean("true"); // true
Boolean.parseBoolean("TrUe"); // true (case-insensitive)
Boolean.parseBoolean("yes"); // false β ONLY "true" is recognised
Common mistakes
- Treating 0 or null as false β Java won't compile that.
- Auto-unboxing a null
BooleanβNullPointerException. UseBoolean.TRUE.equals(x). - Redundant
== trueβif (active == true)is justif (active).
Related
Pillar: Java primitives. See also logical operators and if/else.