Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Booleans

Java Booleans

In programming, there’s frequently a requirement for a data type offering only two potential values, like

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

Java furnishes a boolean data type specifically designed for this purpose, enabling storage of either true or false values.

Boolean Values

Defined with the boolean keyword, a boolean type is limited to containing either the value true or false.

Example

boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun);     // Outputs true
System.out.println(isFishTasty);   // Outputs false
Yet, it's typical to yield boolean values from boolean expressions, primarily for conditional evaluation, as illustrated below.

Boolean Expression

A boolean expression yields either a true or false boolean value.

This functionality is beneficial for constructing logical operations and obtaining answers.

For instance, employing a comparison operator like the greater than (>) operator enables you to ascertain whether an expression or a variable evaluates to true or false.

Example

int x = 10;
int y = 9;
System.out.println(x > y); // returns true, because 10 is higher than 9
Alternatively, it's even simpler.

Example

System.out.println(10 > 9); // returns true, because 10 is higher than 9
In the following examples, we utilize the equal to (==) operator to assess 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

Consider a “real-life scenario” where we need to determine if an individual is eligible to vote.

In the following example, we utilize the >= comparison operator to ascertain if the age (25) surpasses or equals the minimum voting age limit, set at 18.

Example

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

Isn’t that neat? An even more efficient approach (given our momentum) would be to encapsulate the aforementioned code within an if…else statement, allowing us to execute different actions based on the outcome.

Example

If myAge is greater than or equal to 18, print “Old enough to vote!”. Otherwise, print “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.");
}

 

Booleans serve as the foundation for all Java comparisons and conditions, with further exploration into conditions (if…else) slated for the next chapter.