Java Booleans
Working with true and false values in Java
✅ What are Java Booleans?
Java Booleans represent true or false values. They are essential for making decisions in your programs and controlling program flow with conditions and logical operations.
// Boolean variables in Java
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println("Java is fun: " + isJavaFun);
System.out.println("Fish is tasty: " + isFishTasty);
Output:
Java is fun: true
Fish is tasty: false
Boolean Operations
Comparison
Compare values to get boolean results
boolean result = 5 > 3; // true
Logical AND
Both conditions must be true
boolean result = true && false; // false
Logical OR
At least one condition must be true
boolean result = true || false; // true
Logical NOT
Reverse the boolean value
boolean result = !true; // false
🔹 Comparison Operators
Use comparison operators to create boolean expressions:
public class BooleanComparison {
public static void main(String[] args) {
int x = 10;
int y = 5;
// Comparison operators
boolean equal = (x == y); // false (10 == 5)
boolean notEqual = (x != y); // true (10 != 5)
boolean greater = (x > y); // true (10 > 5)
boolean less = (x < y); // false (10 < 5)
boolean greaterEqual = (x >= y); // true (10 >= 5)
boolean lessEqual = (x <= y); // false (10 <= 5)
System.out.println("x equals y: " + equal);
System.out.println("x greater than y: " + greater);
}
}
Output:
x equals y: false
x greater than y: true
🔹 Logical Operators
Combine multiple boolean expressions:
public class LogicalOperators {
public static void main(String[] args) {
int age = 25;
boolean hasLicense = true;
// Logical AND (&&) - both must be true
boolean canDrive = (age >= 18) && hasLicense;
// Logical OR (||) - at least one must be true
boolean isAdult = (age >= 18) || (age >= 21);
// Logical NOT (!) - reverse the value
boolean isMinor = !(age >= 18);
System.out.println("Can drive: " + canDrive);
System.out.println("Is minor: " + isMinor);
}
}
Output:
Can drive: true
Is minor: false
🔹 Boolean in Real Applications
Practical example using booleans for decision making:
public class BooleanExample {
public static void main(String[] args) {
int temperature = 25;
boolean isSunny = true;
boolean hasUmbrella = false;
// Decision making with booleans
boolean goodWeather = (temperature > 20) && isSunny;
boolean needUmbrella = !isSunny && !hasUmbrella;
System.out.println("Good weather for picnic: " + goodWeather);
System.out.println("Need to buy umbrella: " + needUmbrella);
// Using boolean in conditions
if (goodWeather) {
System.out.println("Let's go for a picnic!");
}
}
}
Output:
Good weather for picnic: true
Need to buy umbrella: false
Let's go for a picnic!