Boolean Data Type : Primitive Data Type in Java Programming

boolean Data Type : Primitive Data Type in Java Programming

  1. Boolean is primitive data type in Java.
  2. Boolean data type is used for logical values.
  3. Boolean data type can have two possible values : true or false.
  4. Boolean is the type returned by all relational operators
  5. Boolean is the type required by the conditional expressions used in control statements such as if and for.
  6. “Boolean” is wrapper class for “boolean” primitive data type.

How to Declare & Display Boolean Variable ?

[468x60]
public static void main(String args[]) {
 boolean b1,b2,b3;
 b1 = true;  // Assigning Value
 b2 = false; // Assigning Value
 b3 = b2;    // Assigning Variable
 System.out.println(b1); // Printing Value
 System.out.println(b2); // Printing Value
 System.out.println(b3); // Printing Value
}

Output :

true
false
false

Boolean data type in java programming

Live Example :

// Demonstrate boolean values.
class BoolTest {
  public static void main(String args[]) {
    boolean b1;
    b1 = false;
    System.out.println("b1 is " + b1);
    b1 = true;
    System.out.println("b1 is " + b1);
  // a boolean value can control the if statement
    if(b1) System.out.println("This is executed.");
    b = false;
    if(b)
      System.out.println("Not executed.");
 // outcome of relational operator is a boolean
    System.out.println("100 > 90 is " + (100 > 90));
  }
}

Output :

b1 is false
b1 is true
This is executed.
100 > 90 is true
[468x60]

Different Ways of Using Boolean Value :

Way 1 : Inside If Statement

public static void main(String args[])
{
 boolean b;
 b = true;
 if(b)
   {
   System.out.println("I am True");
   }
}
  • Boolean Value is used to check whether condition is true or not.
  • No need to do == to check equality
public static void main(String args[])
{
 boolean b;
 b = true;
 if(b == true)
   {
   System.out.println("I am True");
   }
}

Way 2 : Comparing Two Numbers

class Demo {
public static void main(String args[]) {
 boolean b;
 b = (10 > 6);
 if(b)
   {
   System.out.println("10 > 6");
   }
 }
}

we can use boolean value to hold the result Comparison operators. here 10 > 6 therefor true will be stored in boolean variable