In programming, there are often scenarios where you need a data type that can only have one of two values, such as:
- YES / NO
- ON / OFF
- TRUE / FALSE
Java provides the boolean data type to store such true or false values.
Boolean Values
A boolean type is declared using the boolean
keyword and can only take the values true or false:
// Example boolean isCarFast = true; boolean isMotorcycleQuiet = false; System.out.println(isCarFast); // Outputs true System.out.println(isMotorcycleQuiet); // Outputs false
However, it’s more common to return boolean values from boolean expressions for conditional testing.
Boolean Expression
A boolean expression evaluates to a boolean value: true or false. This is useful for building logic and finding answers.
For example, you can use a comparison operator, such as the greater than (>) operator, to determine if an expression (or variable) is true or false:
// Example int speedCar = 120; int speedBike = 100; System.out.println(speedCar > speedBike); // returns true, because 120 is greater than 100
Or even more simply:
// Example System.out.println(150 > 100); // returns true, because 150 is greater than 100
In the examples below, we use the equal to (==) operator to evaluate an expression:
// Example int topSpeed = 200; System.out.println(topSpeed == 200); // returns true, because the value of topSpeed is equal to 200 // Example System.out.println(150 == 100); // returns false, because 150 is not equal to 100
Real Life Example
Let’s consider a “real life example” where we need to determine if a vehicle’s speed exceeds the legal speed limit.
In the example below, we use the >= comparison operator to check if the speed (75) is greater than or equal to the speed limit, which is set to 60:
// Example int vehicleSpeed = 75; int speedLimit = 60; System.out.println(vehicleSpeed >= speedLimit); // returns true
An even better approach would be to wrap the code above in an if…else statement, so we can perform different actions depending on the result:
// Example int vehicleSpeed = 75; int speedLimit = 60; if (vehicleSpeed >= speedLimit) { System.out.println("Over the speed limit!"); } else { System.out.println("Within the speed limit."); }