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); // false

Boolean 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); // true

Comparison 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.

OperatorMeaningExample (x = 5)
==Equal tox == 5 is true
!=Not equal tox != 3 is true
>Greater thanx > 8 is false
<Less thanx < 8 is true
>=Greater than or equalx >= 5 is true

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.
Note: The primitive boolean is lowercase, while the object wrapper Boolean is capitalized. For everyday variables and conditions, use the lowercase boolean.

Exercise: Java Booleans

What are the only two possible values a boolean variable can hold?