In Java, the boolean data type represents one of two possible values: true or false. It is a fundamental data type used to represent binary values or logical states, and is often used in conditional expressions, loops, and to control program flow based on conditions.
Notes:
- The boolean type does not have a specific size defined by the language. However, it is typically stored using one bit of memory.
- The default value of a boolean is false.
Basic Declaration and Initialization
You can declare a boolean variable and assign it either true or false:
public class BooleanExample {
public static void main(String[] args) {
boolean isCMotherLanguage= true; // Declare and initialize boolean variable
boolean isJavaOnlyFrontendLanguage = false;
System.out.println("Is C Mother Language of Programming? " + isCMotherLanguage); // true
System.out.println("Is Java Frontend Language? " + isJavaOnlyFrontendLanguage ); // false
}
}
Boolean use in Conditional Statements
boolean values are often used in conditional statements to decide the flow of execution.
public class BooleanExample {
public static void main(String[] args) {
boolean isAdmin = true;
if (isAdmin) {
System.out.println("You are admin.");
} else {
System.out.println("You are not admin.");
}
}
}
Output:
You are admin.
Boolean use with Comparison Operators
You can use comparison operators (like ==, !=, <, >, etc.) to generate boolean values based on conditions.
public class BooleanComparisonExample {
public static void main(String[] args) {
int a = 20;
int b = 10;
boolean result1 = a > b; // true because 20 is greater than 10
boolean result2 = a == b; // false because 20 is not equal to 10
System.out.println("Is a greater than b= " + result1); // true
System.out.println("Is a equal to b= " + result2); // false
}
}
Output:
Is a greater than b= true
Is a equal to b= false
Is a equal to b= false
Boolean use with Logical Operators
Logical operators like && (AND), || (OR), and ! (NOT) can be used to combine or negate boolean expressions.
public class BooleanLogicalExample {
public static void main(String[] args) {
boolean isUser = true;
boolean isAdmin = false;
// Using AND (&&) operator
boolean checkANDCondition= isUser && isAdmin;
System.out.println("Check (AND): " + checkANDCondition); // false
// Using OR (||) operator
boolean checkORCondition = isUser || isAdmin;
System.out.println("Check (OR): " + checkORCondition); // true
// Using NOT (!) operator
boolean isNotAdmin = !isAdmin;
System.out.println("Check (Not): " + isNotAdmin); // true
}
}