loading

Java Booleans

Java Booleans

You will frequently need a data type in programming that can only contain one of two values, such as:

  • YES / NO
  • ON / OFF
  • TRUE / FALSE

Java has a boolean data type that can hold true or false values for this purpose.

Boolean Values

The boolean keyword is used to specify a boolean type, which can only accept the values true or false:

Example

				
					boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun);     // Outputs true
System.out.println(isFishTasty);   // Outputs false
				
			

For conditional testing, it is more typical to return boolean values from boolean expressions (see below).

Boolean Expression

True or false is the boolean value that a Boolean expression yields.

This helps to develop reasoning and uncover solutions.

For instance, to determine whether an expression (or a variable) is true or false, you can use a comparison operator, such as the greater than (>) operator:

Example

				
					int x = 10;
int y = 9;
System.out.println(x > y); // returns true, because 10 is higher than 9
				
			

Alternatively, even simpler:

Example

				
					System.out.println(10 > 9); // returns true, because 10 is higher than 9
				
			

The equal to (==) operator is used in the following examples to evaluate an expression:

Example

				
					int x = 10;
System.out.println(x == 10); // returns true, because the value of x is equal to 10
				
			

Example

				
					System.out.println(10 == 15); // returns false, because 10 is not equal to 15
				
			

Real Life Example

Let’s consider a “real life example” in which determining a person’s voting age is necessary.

The following example shows how to use the >= comparison operator to determine whether the age of 25 is greater than or equal to the 18-year-old voting age limit:

Example

				
					int myAge = 25;
int votingAge = 18;
System.out.println(myAge >= votingAge);
				
			

Nice, huh? Since we are currently winning, an even better strategy would be to enclose the aforementioned code in an if…else statement so that we can do different actions based on the outcome:

Example

If myAge is equal to or greater than 18, then output “Old enough to vote!” In the event when not, output “Not old enough to vote.”

				
					int myAge = 25;
int votingAge = 18;

if (myAge >= votingAge) {
  System.out.println("Old enough to vote!");
} else {
  System.out.println("Not old enough to vote.");
}
				
			

All Java conditions and comparisons are based on booleans.

The following chapter will cover conditions (if…else).



Share this Doc

Java Booleans

Or copy link

Explore Topic