Very often in programming, you will need a data type that can only have one of two values, like:
For this, Java has a boolean data type, which can take the values true or false.
A boolean type is declared with the boolean keyword and can only take the values true or false.
public class Main {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun); // Outputs true
System.out.println(isFishTasty); // Outputs false
}
}
A Boolean expression is a Java expression that returns a Boolean value: true or false.
You can use a comparison operator, such as the greater than > operator, to find out if an expression (or a variable) is true.
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 9;
System.out.println(x > y); // returns true, because 10 is higher than 9
}
}
Booleans are the cornerstone of all conditional logic in Java, which you will learn about in the next chapter.