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:
- 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;
- 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:
- 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!
- 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.
- 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)