Java Boolean Data Type
The boolean type is the simplest data type in Java: it can hold only one of two values, true or false. Despite its size, it is the backbone of every decision your program makes.
Declaring a boolean
A boolean variable stores a single yes-or-no fact. You assign it the literal true or false directly, with no quotation marks, because these are keywords in Java rather than text.
A simple boolean
public class Main {
public static void main(String[] args) {
boolean isRaining = false;
boolean hasTicket = true;
System.out.println(isRaining);
System.out.println(hasTicket);
}
}Booleans from comparisons
Most of the time you do not type true or false yourself. Instead, comparison operators produce a boolean for you. Expressions such as greater-than, less-than, and equals all evaluate to a boolean result you can store or test.
Comparisons return booleans
public class Main {
public static void main(String[] args) {
int age = 20;
boolean isAdult = age >= 18;
System.out.println(isAdult); // true
System.out.println(10 == 5); // false
}
}Operators that work on booleans
Combining boolean values
public class Main {
public static void main(String[] args) {
boolean hasMoney = true;
boolean shopOpen = false;
boolean canBuy = hasMoney && shopOpen;
System.out.println(canBuy); // false
System.out.println(!shopOpen); // true
}
}Booleans drive decisions
The real power of booleans appears in control flow. An if statement runs its block only when the boolean condition inside its brackets is true, which is how your program chooses one path over another.
- A boolean can only ever be true or false, never a number like 1 or 0.
- Name boolean variables as questions, such as isReady or hasAccess, so the code reads naturally.
- The default value of an uninitialised boolean field is false.
- You cannot convert between boolean and int in Java the way some other languages allow.