Boolean Data Type in Java
The Boolean data type is the simplest primitive type in Java. It is used to represent truth values: true or false.
boolean
boolean flag;
- Size (conceptual): 1 bit (but in JVM, it is usually stored as 1 byte = 8 bits, because JVM does not allocate memory smaller than a byte).
- Possible Values:
- true
- false
- Default Value: false
- Usage: Used in conditions, loops, decision-making (if, while, for, etc.), and logical operations.
Internal Representation
- Java does not allow numeric to boolean conversion directly (unlike C/C++, where 0 = false and non-zero = true).
- In JVM, true is internally stored as 1, and false
as 0, but you cannot directly use integers in place of boolean.
Invalid:
boolean b = 1; // Compilation errorCorrect:
boolean b = true;
Example in Java
public class BooleanExample {
public static void main(String[] args) {
boolean isStudentLoggedIn = true; // student has logged into ShikshaSanchar
boolean hasPremiumAccess = false; // free account, no premium access
System.out.println("Is student logged in? " + isStudentLoggedIn);
System.out.println("Does student have premium access? " + hasPremiumAccess);
// Using in conditions
if (isStudentLoggedIn) {
System.out.println("Welcome to ShikshaSanchar!");
}
if (hasPremiumAccess) {
System.out.println("Access granted to premium study materials.");
} else {
System.out.println("Upgrade to premium for exclusive content.");
}
}
}
Output:
Is student logged in? true
Does student have premium access? false
Welcome to ShikshaSanchar!
Upgrade to premium for exclusive content.
Explanation:
- boolean in Java stores only two values: true or false (default = false).
- It is used to represent conditions, decisions, and logical states.
- In this example:
- isStudentLoggedIn = true → prints true, so the message “Welcome to ShikshaSanchar!” is displayed.
- hasPremiumAccess = false → prints false, so instead of premium content, the user sees “Upgrade to premium for exclusive content.”
- Unlike C/C++, Java does not allow numbers to act as booleans (e.g., 1 is not true).
- Thus, booleans are essential for decision-making and control flow in Java programs.
Important Points
- Only true or false are valid for boolean — no integers or strings.
- boolean cannot be typecasted to/from numeric types.
int a = 1; // boolean b = (boolean)a; ❌ Not allowed - Useful in control flow statements if, while, for, do-while.
- Often used with logical operators
- && (AND)
- || (OR)
- ! (NOT)
Summary:
- boolean = 1 bit (conceptually), stored as 1 byte in JVM.
- Values: true or false only.
- Default: false.
- Usage: Widely used in decision-making and logical conditions.