In Java, a Boolean is a data type that can hold one of two possible values: true
or false
. Boolean values are used for logical operations and comparisons in Java programming.
Here’s an example of declaring and using Boolean variables in Java:
boolean isSunny = true; // declaring a Boolean variable named "isSunny" with an initial value of true boolean isRaining = false; // declaring another Boolean variable named "isRaining" with an initial value of false if (isSunny) { System.out.println("It's a sunny day!"); // if the "isSunny" variable is true, print a message } if (!isRaining) { System.out.println("It's not raining."); // if the "isRaining" variable is false, print a message } boolean isWarm = isSunny && !isRaining; // combining Boolean variables with logical operators if (isWarm) { System.out.println("It's warm and sunny!"); // if both "isSunny" and "isRaining" variables are true, print a message }
In the example above, we declared two Boolean variables named isSunny
and isRaining
. We assigned the value true
to the isSunny
variable and false
to the isRaining
variable.
We then used the if
statement to check the value of each variable. The first if
statement checks if the isSunny
variable is true, and if it is, it prints a message to the console. The second if
statement checks if the isRaining
variable is false, and if it is, it prints another message to the console.
Finally, we combined the two Boolean variables using the logical operator &&
(AND). This new Boolean value is stored in the isWarm
variable.
This example shows how Booleans can be used to control the flow of execution in a Java program.