Learn Java

Learn Java Boolean Data Types

Learn Java Boolean Data Types

In Java, the Boolean data type is used to represent a variable that can hold either of two values: true or false.

There are two types of Boolean data types in Java:

  1. Primitive Boolean: The primitive Boolean data type is a built-in data type in Java that can hold only two values: true or false. It is represented by the keyword boolean.

Here is an example of declaring a boolean variable:

 

boolean isSunny = true;

 

  1. Boolean Object: In addition to the primitive boolean data type, there is also a Boolean class in Java that can be used to create a Boolean object.

Here is an example of declaring a Boolean object:

Boolean isSunny = new Boolean(true);

 

Note that the use of Boolean objects is less common than the use of the primitive Boolean data type in Java.

Boolean data types are commonly used in conditional statements, such as if statements and loops, where a certain condition needs to be checked for true or false.

 

Sure, here are some code samples that demonstrate the use of boolean data types in Java:

 

  1. Primitive boolean data type:
public class first {


    public static void main(String[] args) {


        boolean isSunny = true; // declaring a boolean variable
        if (isSunny) { // checking if the value of the variable is true
            System.out.println("It's sunny today!"); // if true, execute this statement
        } else {
            System.out.println("It's not sunny today."); // if false, execute this statement
        }


    }
}

 

Output: It's sunny today!

learn java boolean h4c

 

 

 

  1. Boolean object:
public class first {


    public static void main(String[] args) {


        Boolean isSunny = false; // creating a Boolean object
        if (isSunny.booleanValue()) { // checking if the value of the object is true
            System.out.println("It's sunny today!"); // if true, execute this statement
        } else {
            System.out.println("It's not sunny today."); // if false, execute this statement
        }


    }
}

 

Output: It's not sunny today.

learn java boolean not true h4c

 

 

 

  1. Using a boolean in a for loop condition:
public class first {


    public static void main(String[] args) {


        boolean isSunny = true;
        for (int i = 0; i < 5 && isSunny; i++) { // checking if the value of isSunny is true in the loop condition
            System.out.println("It's sunny today!"); // execute this statement as long as isSunny is true
            isSunny = false; // set isSunny to false after the first iteration
        }


    }
}

 

Output: It's sunny today! (printed once)

learn java Boolean 1 h4c