Booleans are small but powerful tools that control the logic of your entire program. In Java, the
boolean
data type represents only two values:true
orfalse
.
It’s the foundation for all decision-making, conditions, and logical operations in Java.
- The
boolean
type has only two possible values:true
orfalse
. - It is 1 bit conceptually, but usually occupies 1 byte in memory.
- It is used to control program flow, such as with
if
,while
, andfor
loops.
boolean isOnline = true;
boolean isEmpty = false;
Common Boolean Use Cases
Conditional Statements
boolean isAdult = age >= 18;
if (isAdult) {
System.out.println("Access granted.");
} else {
System.out.println("Access denied.");
}
Loop Control
boolean keepRunning = true;
while (keepRunning) {
// loop body
keepRunning = false; // stop after one iteration
}
Logical Expressions
boolean isWeekend = true;
boolean isHoliday = false;
boolean canRelax = isWeekend || isHoliday;
Boolean Operators in Java
Operator | Description | Example | Result | ||||
---|---|---|---|---|---|---|---|
&& |
Logical AND | true && false |
false |
||||
` | ` | Logical OR | `true | false` | true |
||
! |
Logical NOT | !true |
false |
||||
== |
Equality check | x == true |
true if x is true |
||||
!= |
Not equal | x != false |
true if x is true |
Best Practices
- Use meaningful names for boolean variables:
isActive
,hasPermission
,canFly
. - Avoid comparisons like
if (isReady == true)
; preferif (isReady)
. - Use boolean return types in methods for checks and validations.
public boolean isValidEmail(String email) {
return email != null && email.contains("@");
}
Boolean Wrapper Class: Boolean
Java provides a wrapper class for the primitive boolean
:
Boolean flag = Boolean.TRUE;
boolean value = flag.booleanValue();
Useful for collections and objects that require non-primitive types.
Example
public class BooleanExample {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isRainy = false;
if (isJavaFun && !isRainy) {
System.out.println("Let's code with joy!");
}
}
}