Java Booleans
A boolean is a type that holds one of two values. Those two values are true and false.
The two boolean values
One variable holds true. The other variable holds false.
public class Main {
public static void main(String[] args) {
boolean isOpen = true;
boolean isClosed = false;
System.out.println(isOpen);
System.out.println(isClosed);
}
}A comparison produces a boolean
Each line compares two numbers. Each comparison prints its own verdict.
public class Main {
public static void main(String[] args) {
System.out.println(10 > 5);
System.out.println(3 > 7);
}
}A stored comparison
The comparison result goes into a boolean variable. The variable prints the verdict.
public class Main {
public static void main(String[] args) {
int age = 20;
boolean canEnter = age >= 18;
System.out.println(canEnter);
}
}Example
public class Main {
public static void main(String[] args) {
int temperature = 30;
boolean isHot = temperature > 25;
boolean isFreezing = temperature < 0;
System.out.println(isHot);
System.out.println(isFreezing);
}
}Key points
- A boolean variable holds true or false.
- A comparison produces a boolean value.
- The > operator tests whether the left value is the larger one.
- The >= operator tests whether the left value is at least the right value.
- The == operator tests whether two values are equal.
- A comparison result can be stored in a boolean variable.
In this example, temperature holds 30. The first comparison tests whether 30 is greater than 25 and stores true. The second comparison tests whether 30 is below 0 and stores false.
Note
A boolean value prints as the word true or the word false.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which type holds the values true and false?