Learn how to compare values in Java using relational operators. These operators evaluate the relationship between two operands and return a boolean result (true or false).
Java · beginner · 15 min · 9 steps · free
true or false).public class ComparisonDemo {
public static void main(String[] args) {
int a = 15;
int b = 25;
System.out.println("a = 15, b = 25");
// Equal to operator
System.out.println("Is a == b? " + (a == b));
// Not equal to operator
System.out.println("Is a != b? " + (a != b));
// Less than operator
System.out.println("Is a < b? " + (a < b));
// Greater than operator
System.out.println("Is a > b? " + (a > b));
// Less than or equal to operator
System.out.println("Is a <= b? " + (a <= b));
// Greater than or equal to operator
System.out.println("Is a >= b? " + (a >= b));
}
}a with the value 15.b with the value 25.== operator checks for equality. The expression (a == b) evaluates to 15 == 25, which is false.!= operator checks for inequality. The expression (a != b) evaluates to 15 != 25, which is true.< operator checks if the left operand is less than the right. The expression (a < b) evaluates to 15 < 25, which is true.> operator checks if the left operand is greater than the right. The expression (a > b) evaluates to 15 > 25, which is false.<= operator checks if the left operand is less than or equal to the right. The expression (a <= b) evaluates to 15 <= 25, which is true.>= operator checks if the left operand is greater than or equal to the right. The expression (a >= b) evaluates to 15 >= 25, which is false.= (assignment) for comparison instead of == (equality). This is a very common bug, especially in if statements.== due to potential precision errors. It's better to check if their absolute difference is within a small tolerance.== checks for memory id (reference) equality, not content equality. Use .equals() for content comparison.() to group relational expressions within larger, more complex expressions to ensure correct order of operations and improve readability..equals() method to compare the content of objects (like Strings), and == primarily for primitive types or to check if two references point to the exact same object in memory.if (5 == myVar) instead of if (myVar == 5). An accidental if (5 = myVar) would cause a compile-time error.← Arithmetic Operators · Logical Operators (&&, ||, !) →