How to Use Comparison Operators in Java: Syntax and Examples
In Java,
comparison operators like ==, !=, <, >, <=, and >= are used to compare two values and return a boolean result. These operators work with primitive types such as int, double, and char. Use them inside conditions like if statements to control program flow.Syntax
Comparison operators compare two values and return true or false. Here are the common operators:
==: checks if two values are equal!=: checks if two values are not equal<: checks if left value is less than right value>: checks if left value is greater than right value<=: checks if left value is less than or equal to right value>=: checks if left value is greater than or equal to right value
These operators are used between two expressions, for example: a < b.
java
int a = 5; int b = 10; boolean result; result = (a == b); // false result = (a != b); // true result = (a < b); // true result = (a > b); // false result = (a <= b); // true result = (a >= b); // false
Example
This example shows how to use comparison operators in an if statement to decide which number is bigger.
java
public class CompareExample { public static void main(String[] args) { int x = 7; int y = 12; if (x > y) { System.out.println("x is greater than y"); } else if (x < y) { System.out.println("x is less than y"); } else { System.out.println("x is equal to y"); } } }
Output
x is less than y
Common Pitfalls
One common mistake is using == to compare objects like String. This checks if they are the same object, not if their contents are equal. Use .equals() for strings instead.
Also, be careful with floating-point comparisons due to precision issues; avoid direct equality checks with == for float or double.
java
String s1 = "hello"; String s2 = new String("hello"); // Wrong: compares references, not content if (s1 == s2) { System.out.println("Strings are equal"); } else { System.out.println("Strings are not equal"); } // Right: compares content if (s1.equals(s2)) { System.out.println("Strings are equal"); } else { System.out.println("Strings are not equal"); }
Output
Strings are not equal
Strings are equal
Quick Reference
| Operator | Meaning | Example | Result |
|---|---|---|---|
| == | Equal to | 5 == 5 | true |
| != | Not equal to | 5 != 3 | true |
| < | Less than | 3 < 5 | true |
| > | Greater than | 7 > 2 | true |
| <= | Less than or equal to | 4 <= 4 | true |
| >= | Greater than or equal to | 6 >= 7 | false |
Key Takeaways
Use comparison operators like ==, !=, <, >, <=, >= to compare primitive values in Java.
Comparison operators return a boolean value: true or false.
For objects like String, use .equals() instead of == to compare content.
Avoid using == for floating-point equality due to precision issues.
Comparison operators are commonly used in if statements to control program flow.