✅ 1. What is a Boolean?
A boolean is a data type that has only two possible values: true or false.
Booleans are used to make decisions in programs, control flow, and test conditions.
boolean isRaining = true;
boolean finishedHomework = false;
✅ 2. Boolean Expressions
A boolean expression is any expression that evaluates to true or false.
5 > 3 // true
10 == 2 // false
age >= 18 // depends on the value of age
Example: score >= 70
✅ 3. Comparison Operators
These operators compare values and return a boolean result.
| Operator | Meaning | Example |
|---|---|---|
== | equal to | a == b |
!= | not equal to | a != b |
> | greater than | a > b |
< | less than | a < b |
>= | greater than or equal | a >= b |
<= | less than or equal | a <= b |
int score = 85;
boolean passed = score >= 70; // true
✅ 4. Logical Operators
Logical operators combine multiple boolean expressions.
AND (&&)
Returns true only if both conditions are true.
(age > 16 && hasLicense)
| A | B | A && B |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
OR (||)
Returns true if at least one condition is true.
(isWeekend || isHoliday)
| A | B | A || B |
|---|---|---|
| true | true | true |
| true | false | true |
| false | true | true |
| false | false | false |
NOT (!)
Reverses a boolean value.
!true // false
!false // true
boolean loggedIn = false;
if (!loggedIn) {
System.out.println("Please login.");
}
✅ 5. Using Boolean Logic in IF Statements
Boolean expressions are commonly used in decision making.
Basic IF Statement
if (temperature > 90) {
System.out.println("It's hot outside!");
}
IF-ELSE Example
if (score >= 70) {
System.out.println("You passed.");
} else {
System.out.println("You failed.");
}
✅ 6. Combining Multiple Conditions
if (age >= 16 && hasPermit) {
System.out.println("Eligible to drive.");
}
✅ 7. Order of Boolean Operations
Java evaluates logical expressions in this order:
- Parentheses ()
- NOT !
- AND &&
- OR ||
boolean result = true || false && false;
// evaluates as: true || (false && false) => true || false => true
✅ 8. Short-Circuit Evaluation (Important Concept)
Java may stop evaluating early if the result is already known. This can make code faster and prevent errors.
AND Example
if (false && something()) {
// something() will NOT run
}
OR Example
if (true || something()) {
// something() will NOT run
}
✅ 9. Common Beginner Mistakes
if (a = 5) // WRONG
✅ Correct:
if (a == 5)
if age > 18 // WRONG
✅ Correct:
if (age > 18)
if (isReady == true) // not needed
Better:
if (isReady)
✅ 10. Real-World Example Program
public class BooleanExample {
public static void main(String[] args) {
int age = 17;
boolean hasID = true;
if (age >= 16 && hasID) {
System.out.println("Allowed entry.");
} else {
System.out.println("Not allowed.");
}
}
}
🎯 Summary
Boolean logic allows programs to:
- Make decisions
- Compare values
- Control program flow
- Combine multiple conditions
Key operators:
== != > < >= <=
&& || !