Java Booleans
Use the boolean type in Java to represent true/false values and form conditional logic.
boolean is the simplest primitive: it has exactly two values, true and false. Every conditional in Java — if, while, the ternary ?:, the operands of && and || — wants a boolean. You don't have to know much about the type, but knowing the difference between boolean and Boolean saves a future bug.
Declaring a boolean
boolean isOpen = true;
boolean ready = false;
boolean canPay = (balance >= amount);The keywords are true and false — lowercase. There's no True, no TRUE, no 1, no 0 — Java is strict.
Booleans in conditions
Every if, while, do-while, and the middle clause of a for loop expects a boolean:
boolean isAdult = age >= 18;
if (isAdult) {
System.out.println("Welcome!");
}
while (!stopRequested) {
process();
}You cannot use a number where a boolean is required:
int x = 5;
// if (x) { ... } // compile error: int is not a boolean
if (x != 0) { ... } // OKThat's a feature, not an inconvenience — it eliminates a whole family of C bugs.
Boolean operations
The three logical operators (Logical Operators):
boolean a = true && false; // false
boolean b = true || false; // true
boolean c = !true; // false&& and || short-circuit. & and | evaluate both sides — almost never what you want on booleans.
Boolean — the wrapper
The wrapper class Boolean lets you put booleans into collections and pass them around as objects:
List<Boolean> answers = new ArrayList<>();
answers.add(true);
answers.add(false);
Map<String, Boolean> flags = new HashMap<>();
flags.put("debug", true);Autoboxing converts between boolean and Boolean automatically. The one thing to watch out for: a Boolean reference can be null, but a primitive boolean can't.
Boolean maybe = null;
if (maybe) { ... } // throws NullPointerException — autounbox on nullUse Boolean.TRUE.equals(maybe) or an explicit null check if null is possible.
Parsing booleans
Boolean.parseBoolean(s) returns true if the string is "true" (case-insensitive), and false for everything else — including misspellings and unexpected values:
Boolean.parseBoolean("true"); // true
Boolean.parseBoolean("TRUE"); // true
Boolean.parseBoolean("yes"); // false
Boolean.parseBoolean("1"); // false
Boolean.parseBoolean(null); // falseIf you need strict input validation, write your own check rather than trusting this method's "everything-not-true-is-false" semantics.
boolean[] vs BitSet
For a few booleans, a boolean[] is fine and reads clearly:
boolean[] flags = new boolean[8];
flags[3] = true;For thousands or millions of flags, BitSet is more memory-efficient — it packs flags into longs internally:
import java.util.BitSet;
BitSet seen = new BitSet();
seen.set(42);
System.out.println(seen.get(42)); // trueA demonstration
What's next
Java Characters (char) — the 16-bit primitive that holds a single Unicode code unit.
Practice
Which is a valid boolean expression in Java?