Java Booleans
In this page:
The boolean Type
The boolean type represents exactly one of two possible values, true or false, and is Java's smallest data type conceptually, used whenever a piece of information is a simple yes-or-no or on-or-off flag.
Example: The boolean Type
public class Main {
public static void main(String[] args) {
boolean isOpen = true; // simple yes/no flag
System.out.println(isOpen);
}
}
Login to try C/C++/Java/PHP code in the editor
Boolean Expressions
A boolean expression is any expression that evaluates to true or false, most commonly formed by comparing two values with operators like >, <, ==, or != rather than by writing a literal true or false directly.
Example: Boolean Expressions
public class Main {
public static void main(String[] args) {
boolean isAdult = 20 > 18; // comparison, not a literal true/false
System.out.println(isAdult);
}
}
Login to try C/C++/Java/PHP code in the editor
Booleans in Conditions
Boolean values are what control flow statements like if, while, and for actually test: an if statement runs its block only when the boolean expression inside its parentheses evaluates to true.
Example: Booleans in Conditions
public class Main {
public static void main(String[] args) {
boolean loggedIn = true;
if (loggedIn) {
System.out.println("Runs only because loggedIn is true");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Boolean Variables from Comparisons
Storing the result of a comparison in a named boolean variable, rather than repeating the comparison inline, makes conditions easier to read and lets the same computed result be reused in multiple places.
Example: Boolean Variables from Comparisons
public class Main {
public static void main(String[] args) {
int score = 75;
boolean passed = score >= 60; // named result, reused below
System.out.println(passed);
System.out.println("Result: " + passed);
}
}
Login to try C/C++/Java/PHP code in the editor
Default Boolean Value
An uninitialized boolean instance or static field automatically defaults to false, and every element of a newly created boolean array also starts out as false until a value is explicitly assigned.
Example: Default Boolean Value
public class Main {
static boolean flag; // uninitialized instance field
public static void main(String[] args) {
boolean[] flags = new boolean[3];
System.out.println(flag); // defaults to false
System.out.println(flags[0]); // array elements default to false too
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: