Java Booleans

In programming, there are often scenarios where you need a data type that can only have one of two values, such as:

Tutorials dojo strip
  • 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:

JAVA

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:

JAVA

Or even more simply:

JAVA

In the examples below, we use the equal to (==) operator to evaluate an expression:

JAVA




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:

JAVA

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:

JAVA

Tutorials dojo strip