Java Boolean

Boolean is a java data type that has possible two values: True and false.

True can be referred: YES and ON
False can be referred: NO and OFF

Sometimes in programing, we need to hold or show True or False values based on our requirements.

Like: Is it leap year? Yes/No
Are you allowed to vote? Yes/No
Are You male? Yes/No
Is that book available in the book store? Yes/No...
Like for thousands of use cases, provably we need to present or execute Boolean values. Even any simple expression also prints boolean values.

# Create boolean variable


public class Main{
  public static void main (String[] args) {
    Boolean isJavaDifficult = true;
    Boolean isJavaEasy = false;
    
    //print the boolean values
    System.out.println(isJavaDifficult);
    System.out.println(isJavaEasy);
  }
}
/**
 * true
 * false
 */

# Expression that prints boolean values


public class Main{
  public static void main (String[] args) {
    int x = 99; 
    int y = 100; 
    
    //print the boolean values
    System.out.println(x > y);
    System.out.println(x < y);
  }
}
/**
 * false 
 * true
 */
 

There is no need to create variables too.


public class Main{
  public static void main (String[] args) {
    //boolean expression 
    System.out.println( 10 < 20);
    System.out.println(10 == 20);
    System.out.println(10 != 20);
    System.out.println(10 > 20);
  }
}
/**
 * true 
 * false
 * true
 * false
 */
 

# Real life examples (based on boolean expression)

An example could be of boolean expression is that, a person is enough old to vote or not.

We know that, a person must be at least 18 or above to vote in many countries.

Let's check out the below example:


public class Main{
  public static void main (String[] args) {
    int myAge = 30; 
    int ageRequired = 18;
   
    System.out.println(myAge >=ageRequired);
  }
}
/**
 * Output: 
 * true
 */

As it returns true, it means you are allowed to vote.

Another example could be checking the leap year. If the month February is 29 days then it is a leap year otherwise not.


public class Main{
  public static void main (String[] args) {
    int daysOfMonth = 28;
    int requiredDaysOfMonth = 29;
    System.out.println(daysOfMonth == requiredDaysOfMonth );
  }
}
/**
 * Output: 
 * false
 */

Means, it is not a leap year.

# if - else statements
If the condition of if block is true then, the code block if will be executed otherwise, it prints the else block. Such as


public class Main{
  public static void main (String[] args) {
    int age = 25; 
    int requiredAge = 18; 
    if(age >= requiredAge){
      System.out.println("You are allowed to vote.");
    }
    else {
      System.out.println("You are not allowed to vote.");
    }
  }
}
/**
 * Output: 
 * You are allowed to vote.
 */