Java Booleans - Complete Guide
Introduction to Boolean Data Type
In Java, the boolean data type represents logical values with only two possible states: true or false. Booleans are essential for decision-making and control flow in programs.
They are most often produced by comparison operators or logical expressions, and are widely used in conditional statements such as if, while, and for loops.
Boolean Declaration and Usage
Boolean variables can be declared, initialized, and used directly in logical expressions. Instance variables of type boolean default to false if not explicitly initialized.
public class BooleanBasics {
public static void main(String[] args) {
// Boolean declarations
boolean isJavaFun = true;
boolean isProgrammingHard = false;
System.out.println("Is Java fun? " + isJavaFun);
System.out.println("Is programming hard? " + isProgrammingHard);
// Boolean expression from comparison
int age = 25;
boolean isAdult = age >= 18;
boolean canVote = isAdult && isJavaFun;
System.out.println("Is adult? " + isAdult);
System.out.println("Can vote? " + canVote);
// Default value for instance variables
BooleanWrapper wrapper = new BooleanWrapper();
System.out.println("Default boolean: " + wrapper.defaultBoolean);
}
}
class BooleanWrapper {
boolean defaultBoolean; // Defaults to false
}
Is Java fun? true Is programming hard? false Is adult? true Can vote? true Default boolean: false
Logical Operators
Java supports three main logical operators for combining boolean values: AND (&&), OR (||), and NOT (!). These operators follow short-circuit evaluation rules, meaning the second operand may not be evaluated if the result can be determined from the first.
public class LogicalOperators {
public static void main(String[] args) {
// AND operator
System.out.println("true && true: " + (true && true));
System.out.println("true && false: " + (true && false));
// OR operator
System.out.println("true || false: " + (true || false));
System.out.println("false || false: " + (false || false));
// NOT operator
System.out.println("!true: " + (!true));
System.out.println("!false: " + (!false));
// Short-circuit evaluation
int x = 5;
boolean result1 = (x > 10) && (x++ < 20); // second part not evaluated
System.out.println("Result1: " + result1 + ", x: " + x);
boolean result2 = (x < 10) || (x++ > 5); // second part not evaluated
System.out.println("Result2: " + result2 + ", x: " + x);
}
}
true && true: true true && false: false true || false: true false || false: false !true: false !false: true Result1: false, x: 5 Result2: true, x: 5
Comparison Operators
Comparison operators in Java return boolean results. They can test for equality, inequality, and relative ordering between numbers. When working with objects such as strings, the equals() method should be used for content comparison instead of ==.
public class ComparisonOperators {
public static void main(String[] args) {
int x = 10;
int y = 5;
int z = 10;
// Equality and inequality
System.out.println("x == y: " + (x == y));
System.out.println("x == z: " + (x == z));
System.out.println("x != y: " + (x != y));
// Relational comparisons
System.out.println("x > y: " + (x > y));
System.out.println("x < y: " + (x < y));
System.out.println("x >= z: " + (x >= z));
System.out.println("y <= x: " + (y <= x));
// String comparison
String str1 = "hello";
String str2 = "hello";
String str3 = new String("hello");
System.out.println("str1 == str2: " + (str1 == str2));
System.out.println("str1 == str3: " + (str1 == str3));
System.out.println("str1.equals(str3): " + str1.equals(str3));
// Floating-point comparison with tolerance
double d1 = 0.1 + 0.2;
double d2 = 0.3;
System.out.println("d1 == d2: " + (d1 == d2));
System.out.println("Math.abs(d1 - d2) < 0.0001: " + (Math.abs(d1 - d2) < 0.0001));
}
}
x == y: false x == z: true x != y: true x > y: true x < y: false x >= z: true y <= x: true str1 == str2: true str1 == str3: false str1.equals(str3): true d1 == d2: false Math.abs(d1 - d2) < 0.0001: true
Boolean in Control Flow
Booleans are fundamental in controlling the execution of code blocks. They are used in if-else statements, loops, and ternary operations to direct program behavior.
public class BooleanControlFlow {
public static void main(String[] args) {
int score = 85;
boolean hasPassed = score >= 60;
boolean hasExcellentScore = score >= 90;
// If-else statement
if (hasPassed) {
System.out.println("Congratulations! You passed.");
} else {
System.out.println("Sorry, you failed.");
}
// Ternary operator
String result = hasExcellentScore ? "Excellent!" : "Good job";
System.out.println("Result: " + result);
// While loop using boolean flag
boolean isRunning = true;
int counter = 0;
while (isRunning) {
counter++;
System.out.println("Counter: " + counter);
if (counter >= 5) {
isRunning = false;
}
}
// Combined conditions
boolean isWeekend = false;
boolean isHoliday = true;
if (isWeekend || isHoliday) {
System.out.println("Time to relax!");
} else {
System.out.println("Time to work!");
}
}
}
Congratulations! You passed. Result: Good job Counter: 1 Counter: 2 Counter: 3 Counter: 4 Counter: 5 Time to relax!