Comparison Operators
Comparison operators (relational operators) are used to compare two
values. The result of any comparison operation is always a boolean
value: either true or false.
The 6 Comparison Operators
Java provides six standard operators for comparing primitive values:
| Operator | Name | Example (assume x=5, y=3) | Result |
|---|---|---|---|
== |
Equal to | x == y |
false |
!= |
Not equal to | x != y |
true |
> |
Greater than | x > y |
true |
< |
Less than | x < y |
false |
>= |
Greater than or equal to | x >= y |
true |
<= |
Less than or equal to | x <= y |
false |
Output
Click Run to execute your code
Common Pitfalls
1. Assignment (=) vs Equality (==)
Problem: Using a single equals sign = instead
of double equals ==.
// Wrong
if (x = 5) { ... } // Compiler error! (Assignment, not boolean)
// Correct
if (x == 5) { ... } // Comparison
Comparing Objects: Be very careful when comparing objects (like
String) with ==.
- For primitives (int, char, boolean),
==compares values. - For objects (Strings, Arrays),
==compares memory addresses (references).
To compare String content, always use .equals().
String s1 = "Hello";
String s2 = new String("Hello");
System.out.println(s1 == s2); // false (different objects)
System.out.println(s1.equals(s2)); // true (same content)
Summary
- Comparison operators always return a
booleanresult. - Use
==for equality and!=for inequality. - Use
>,<,>=,<=for range checks. - Do not confuse
=(assignment) with==(equality). - Use
.equals()when comparing Strings, not==.
Enjoying these tutorials?