Booleans:
In Java, boolean is a distinct data type unlike in some other programming languages like C language, in which we use integers to represent boolean values.
Booleans store one of the two values:
- True / False
- On / Off
- Yes / No
booleans.java
public class Main {
public static void main(String[] args) {
boolean isTrue = true;
System.out.println(isTrue);
boolean isFalse = false;
System.out.println(isFalse);
}
}
Booleans and Logical Operators:
We use booleans usually with logical operators to perform logical operations.booleans.java
public class Main {
public static void main(String[] args) {
boolean a = true;
boolean b = false;
boolean resultAnd = a && b;
System.out.println(resultAnd)
boolean resultOr = a || b;
System.out.println(resultOr)
boolean resultNot = !a;
System.out.println(resultNot)
}
}
Booleans and Conditional Statements:
Booleans are commonly used in conditional statements like if, if else, while and do while loops to control the flow of the program based on the condition.booleans.java
public class Main {
public static void main(String[] args) {
boolean isTrue = true;
if (isTrue) {
System.out.println("Condition is true");
} else {
System.out.println("Condition is false");
}
}
}
Booleans and Comparison Operators:
Comparison operators always return boolean values.booleans.java
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 10;
boolean isEqual = (x == y);
System.out.println(isEqual);
boolean isNotEqual = (x != y);
System.out.println(isNotEqual);
}
}
Note : Boolean data type in Java is used for storing values that can be either true or false. Booleans often go hand-in-hand with logical operators to perform logical operations.