Java Comparison Operators
Comparison operators ask questions about two values and always answer with a boolean, either true or false. They are the backbone of decision-making in Java, feeding directly into if statements and loops.
The six comparison operators
Each comparison operator takes two operands and returns a boolean. The table below lists all six, with a sample result assuming a is 8 and b is 5.
Storing comparison results
Because a comparison produces a boolean, you can store it in a boolean variable and print it, or use it directly. Beginners often forget that these operators return a value rather than doing anything on their own.
Comparisons produce booleans
public class Main {
public static void main(String[] args) {
int age = 20;
boolean isAdult = age >= 18;
boolean isTeenager = age < 13;
System.out.println(isAdult); // true
System.out.println(isTeenager); // false
}
}Comparisons inside an if statement
The most common place you will use comparisons is inside an if statement, where Java runs a block of code only when the condition is true. Here we check whether a score passes a threshold.
Driving a decision
public class Main {
public static void main(String[] args) {
int score = 72;
if (score >= 50) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
// prints: Pass
}
}