Java Booleans
A boolean is the simplest data type in Java: it can hold only one of two values, true or false. Booleans power the decisions your programs make, driving if statements, loops, and any logic that asks a yes-or-no question.
Declaring a Boolean
You declare a boolean with the keyword boolean (lowercase) and assign it either true or false. These two literals are not Strings, so they never appear in quotes. A boolean variable is often used to remember a state, such as whether a user is logged in.
Boolean variables
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun); // true
System.out.println(isFishTasty); // falseBoolean Expressions
Most booleans are not typed by hand; they come from comparisons. A boolean expression is any piece of code that Java evaluates to true or false, such as comparing two numbers with the greater-than or equal-to operators.
Comparisons produce booleans
int age = 20;
System.out.println(age > 18); // true
System.out.println(age == 21); // false
System.out.println(age <= 20); // trueComparison Operators
The operators below each return a boolean result. Notice that equality uses two equals signs (==); a single equals sign is assignment and would not compare anything.
Using a Boolean to Decide
The real value of booleans appears inside if statements. The condition in the parentheses must be a boolean, and Java runs the block only when that condition is true.
A boolean condition in action
int temperature = 30;
boolean isWarm = temperature > 25;
if (isWarm) {
System.out.println("It is a warm day.");
} else {
System.out.println("Bring a jacket.");
}- A boolean holds only true or false, never anything else.
- Comparison operators such as > and == evaluate to a boolean.
- Use == to compare, and a single = only to assign a value.
- Booleans are the fuel for if statements, while loops, and other logic.
Exercise: Java Booleans
What are the only two possible values a boolean variable can hold?