Relational Operators in Java – Explained with Examples
Relational operators, also called comparison operators, compare two values and return a boolean: true or false. They answer questions like "is the balance enough?", "are these equal?" or "is the score at least 40?", and they appear in almost every if statement and loop.
This tutorial covers Java's six relational operators, how they work with different types, the important difference between == and equals() for objects, and how to compare decimal numbers safely.
1. The Six Relational Operators
| Operator | Meaning | Example (a = 10, b = 20) | Result |
|---|---|---|---|
== | Equal to | a == b | false |
!= | Not equal to | a != b | true |
> | Greater than | a > b | false |
< | Less than | a < b | true |
>= | Greater than or equal to | a >= 10 | true |
<= | Less than or equal to | b <= 15 | false |
public class RelationalBasics {
public static void main(String[] args) {
int a = 10, b = 20;
System.out.println("a == b : " + (a == b));
System.out.println("a != b : " + (a != b));
System.out.println("a > b : " + (a > b));
System.out.println("a < b : " + (a < b));
System.out.println("a >= 10: " + (a >= 10));
System.out.println("b <= 15: " + (b <= 15));
// Mixed types are promoted before comparing
System.out.println("10 == 10.0 : " + (10 == 10.0));
System.out.println("'A' < 'a' : " + ('A' < 'a') + " (65 < 97)");
// The result is a boolean you can store
int marks = 72;
boolean passed = marks >= 40;
System.out.println("passed = " + passed);
}
}
a == b : false a != b : true a > b : false a < b : true a >= 10: true b <= 15: false 10 == 10.0 : true 'A' < 'a' : true (65 < 97) passed = true
- Numbers of different types are promoted before comparison, so
10 == 10.0istrue. charvalues compare by their Unicode codes: uppercase letters (65–90) come before lowercase letters (97–122).<,>,<=and>=work only on numbers andchar;==and!=also work on booleans and references.
2. == vs equals() for Objects
For objects, == checks whether two references point to the same object. To compare the contents, use equals(). This is one of the most common sources of bugs in Java:
public class ObjectEquality {
public static void main(String[] args) {
String s1 = "java";
String s2 = "java"; // same pooled literal
String s3 = new String("java"); // a new object
System.out.println("s1 == s2 : " + (s1 == s2));
System.out.println("s1 == s3 : " + (s1 == s3));
System.out.println("s1.equals(s3) : " + s1.equals(s3));
System.out.println("equalsIgnoreCase: " + "JAVA".equalsIgnoreCase(s1));
Integer x = 500, y = 500;
System.out.println("Integer 500 == 500 : " + (x == y));
System.out.println("x.equals(y) : " + x.equals(y));
// Ordering objects uses compareTo, not < or >
System.out.println("\"apple\".compareTo(\"banana\") < 0 : " + ("apple".compareTo("banana") < 0));
}
}
s1 == s2 : true
s1 == s3 : false
s1.equals(s3) : true
equalsIgnoreCase: true
Integer 500 == 500 : false
x.equals(y) : true
"apple".compareTo("banana") < 0 : true
s1 == s2is true only because identical string literals share one pooled object. Strings built at runtime usually do not.Integervalues outside −128…127 are separate objects, so==fails whileequals()works.- To order objects, use
compareTo()(or aComparator): a negative result means "less than", zero "equal", positive "greater than". Objects.equals(a, b)compares safely even when one of them isnull.
3. Comparing Floating-Point Numbers
Because many decimal values cannot be stored exactly in binary, comparing double values with == is unreliable:
public class FloatingCompare {
public static void main(String[] args) {
double sum = 0.1 + 0.2;
System.out.println("0.1 + 0.2 == 0.3 : " + (sum == 0.3));
double epsilon = 1e-9;
System.out.println("close enough : " + (Math.abs(sum - 0.3) < epsilon));
double nan = 0.0 / 0;
System.out.println("NaN == NaN : " + (nan == nan));
System.out.println("Double.isNaN : " + Double.isNaN(nan));
System.out.println("Double.compare(1.5, 2.5) = " + Double.compare(1.5, 2.5));
System.out.println("-0.0 == 0.0 : " + (-0.0 == 0.0));
}
}
0.1 + 0.2 == 0.3 : false close enough : true NaN == NaN : false Double.isNaN : true Double.compare(1.5, 2.5) = -1 -0.0 == 0.0 : true
- Compare with a small tolerance (epsilon):
Math.abs(a - b) < 1e-9. NaNis never equal to anything, not even itself; test withDouble.isNaN().Double.compare()gives a consistent ordering, including forNaNand-0.0.- For money, use
BigDecimaland itscompareTo()method (equals()also compares scale, so2.0and2.00differ).
4. Precedence and Chaining
Relational operators have lower precedence than arithmetic, so a + 5 > b * 2 computes both sides first. <, >, <=, >= bind tighter than == and !=. Java does not support chained comparisons: 1 < x < 10 does not compile; write x > 1 && x < 10.
5. Where Relational Operators Are Used
if (balance >= amount) { withdraw(amount); } // decisions
for (int i = 0; i < items.length; i++) { ... } // loop conditions
boolean isTeen = age >= 13 && age <= 19; // combined with logical operators
String label = stock > 0 ? "In stock" : "Sold out"; // ternary expressions
list.stream().filter(p -> p.price() < 500) // stream filters
6. Common Mistakes
- Comparing strings with
==instead ofequals(). - Using
=(assignment) instead of==. - Comparing
doubleresults with==. - Writing chained comparisons like
a < b < c. - Unboxing a
nullIntegerin a comparison, which throwsNullPointerException.
7. Summary
- Java has six relational operators:
==,!=,>,<,>=and<=; each returns a boolean. - Operands of different numeric types are promoted before comparison.
- For objects,
==compares references; useequals()for contents andcompareTo()for ordering. - Compare decimals with a tolerance or
BigDecimal, and checkNaNwithDouble.isNaN().
Related Tutorials
Frequently Asked Questions (FAQ)
Q1. What are relational operators in Java?
Operators that compare two values and return a boolean: ==, !=, >, <, >= and <=.
Q2. What is the difference between == and equals()?
== compares primitive values, or for objects whether two references point to the same object. equals() compares the logical content of objects as defined by the class.
Q3. How do I compare two strings in Java?
Use s1.equals(s2) for exact equality, equalsIgnoreCase() to ignore case, and compareTo() to sort alphabetically. Do not use ==.
Q4. Why does "java" == "java" return true sometimes?
Identical string literals are stored once in the string pool, so both references point to the same object. Strings created at runtime, for example with new String() or concatenation of variables, are separate objects.
Q5. Can I use < or > with strings?
No. Relational ordering operators only work on numeric types and char. For strings use compareTo().
Q6. What is the result type of a relational expression?
Always boolean.
Q7. How should I compare double values?
Check whether their difference is smaller than a tolerance, for example Math.abs(a - b) < 1e-9, or use BigDecimal for exact decimal arithmetic.
Q8. Why is NaN == NaN false?
By the IEEE 754 standard, NaN is not equal to any value, including itself. Use Double.isNaN(x) to test for it.
Q9. Can I compare a char with an int?
Yes. The char is promoted to its Unicode number, so 'A' == 65 is true.
Q10. Can I compare booleans with relational operators?
Only with == and !=. Booleans have no order, so < and > do not apply.
Q11. Why does Integer x = 500, y = 500; x == y return false?
Autoboxing caches Integer objects only for values −128 to 127. For 500, two different objects are created, so == compares different references. Use equals().
Q12. Is 1 < x < 10 valid in Java?
No. 1 < x produces a boolean, which cannot be compared with 10. Write x > 1 && x < 10.
Q13. What does compareTo() return?
A negative number if the object is less than the argument, zero if they are equal in order, and a positive number if it is greater.
Q14. How do I compare objects that might be null?
Use Objects.equals(a, b), which returns true if both are null and avoids calling a method on a null reference.
Q15. What is the precedence of relational operators?
Lower than arithmetic and shift operators, higher than logical operators. <, >, <=, >= are evaluated before == and !=.
Q16. Is -0.0 equal to 0.0?
With ==, yes. Double.compare(-0.0, 0.0) and Double.equals() treat them as different, which matters when sorting.
Q17. How do I compare two arrays?
== compares references. Use Arrays.equals(a, b) for element-by-element comparison, or Arrays.deepEquals() for nested arrays.
Q18. Should I compare BigDecimal with equals()?
Usually not. equals() also compares scale, so 2.0 and 2.00 are not equal. Use a.compareTo(b) == 0 to compare numeric values.
Q19. Can relational operators be used with enums?
== and != are the recommended way to compare enum constants. For ordering, use compareTo() or ordinal().
Q20. What happens when comparing int and long?
The int is promoted to long and the values are compared numerically, so 5 == 5L is true.