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().