boolean in Java
Only true/false; no conversion to or from numbers.
if (1) means true. In Java it won't even compile. Is Java being stubborn, or saving you from a famous bug?Just two values
A boolean holds true or false, nothing else. The conditions of if, while and for must be boolean expressions.
boolean ready = true;
boolean done = 3 > 5; // false
if (ready) {
System.out.println("Go!");
}No numbers allowed
Unlike C, Java has no conversion between booleans and numbers: 0 is not false, 1 is not true. There's no cast like (int) ok, and ok + 0 doesn't compile either.
Your turn
What happens?
int lives = 1;
if (lives) {
System.out.println("alive");
}aliveCompile errorNothing is printed
Show the answer
Compile error. lives is an int, and an int is not a condition. Write if (lives > 0).
Need a number?
You have boolean ok and need 1 when it's true and 0 when it's false. Casting is forbidden. How?
Think about it, then reveal the answer
Use the ternary operator: ok ? 1 : 0. It picks the number explicitly. (More on ? : in World 3.)
= vs ==
= assigns. done = true stores true, and the assignment's value is true, so the branch always runs. It compiles only because done is a boolean; if (x = 5) with an int is a compile error. Just write if (done).
boolean done = false;
if (done = true) { // assigns!
System.out.println("yes");
}Text to boolean
Boolean.parseBoolean(s) returns true only when s is "true", ignoring case. Anything else, including "yes", "1" and even null, gives false, with no exception.
Boolean.parseBoolean("TRUE") // true
Boolean.parseBoolean("yes") // false
Boolean.parseBoolean(null) // falseIn real projects
A config file says FEATURE_ENABLED=yes, parseBoolean quietly returns false, and the team spends an afternoon asking why the feature is off. Real code validates config values instead of trusting them.
Key takeaways
- Only two values: true and false
- No casts between boolean and int
- if, while and for conditions must be boolean
- Use cond ? 1 : 0 to turn a boolean into a number
The boolean is named after George Boole, whose 1854 book on the "Laws of Thought" described the algebra of true and false that every computer now runs on.
Practice questions
What does this print?
int flag = 1;
if (flag) {
System.out.println("on");
}- on
- Compile error
- Nothing is printed
- Throws ClassCastException
Check your answer
Compile error. flag is an int, and Java doesn't convert ints to booleans. Write if (flag == 1) or make flag a boolean.
You have `boolean ok` and need the number 1 if it's true and 0 if it's false. Which expression works?
- (int) ok
- Integer.valueOf(ok)
- ok ? 1 : 0
- ok + 0
Check your answer
ok ? 1 : 0. There is no cast from boolean to int, and + isn't defined for booleans and numbers. The ternary operator picks the number explicitly.