Java Booleans
Many questions in a program have only two possible answers: is the user logged in? Is the number even? Is the shop open? Java has a special data type for such answers, boolean, with exactly two values: true and false.
Boolean variables
public class Main {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun);
System.out.println(isFishTasty);
}
}true false
Name boolean variables like a yes-or-no question: isReady, hasTicket, canVote. Then the code reads almost like English.
Comparisons give booleans
Every comparison from the Operators topic produces a boolean. You can print it or store it in a variable:
public class Main {
public static void main(String[] args) {
int x = 10, y = 9;
System.out.println(x > y);
System.out.println(x == 10);
System.out.println(x != y);
boolean isEven = x % 2 == 0;
System.out.println("10 is even: " + isEven);
}
}true true true 10 is even: true
Combining booleans
With && (and), || (or) and ! (not) you build bigger conditions from small ones. A small table of all cases is called a truth table:
| a | b | a && b | a || b | !a |
|---|---|---|---|---|
| true | true | true | true | false |
| true | false | false | true | false |
| false | true | false | true | true |
| false | false | false | false | true |
public class Main {
public static void main(String[] args) {
int age = 19;
boolean hasId = true;
boolean member = false;
boolean canEnter = age >= 18 && hasId;
boolean getsDiscount = member || age < 21;
System.out.println("Can enter: " + canEnter);
System.out.println("Discount: " + getsDiscount);
System.out.println("Not a member: " + !member);
}
}Can enter: true Discount: true Not a member: true
Storing a long condition in a well-named variable, like canEnter, makes the program much easier to read than repeating the whole expression.
Booleans and decisions
The real power of booleans comes with decisions. An if statement runs a block only when its condition is true. You will learn it properly in the next topics, User Input and If ... Else, but here is a first taste:
public class Main {
public static void main(String[] args) {
int temperature = 31;
boolean isHot = temperature > 30;
if (isHot) {
System.out.println("Drink plenty of water!");
}
System.out.println("Have a nice day.");
}
}Drink plenty of water! Have a nice day.
Note that you write if (isHot), not if (isHot == true): the variable already is true or false.
Practice exercises
- Store whether 2025 is a leap year in a boolean (
year % 4 == 0 && year % 100 != 0 || year % 400 == 0) and print it. - Make two booleans
hasUmbrellaandisRainingand print whether you will get wet. - Print the truth table of
&&for all four combinations of two booleans.