Comparison Operators in Java
Java's six comparison operators — ==, !=, <, >, <=, >= — each evaluate to a boolean, making them the building blocks of every conditional and loop. For primitives, == and != compare actual values directly, exactly as expected.
For objects, including String, == and != compare references — whether two variables point to the same object in memory — not content. That's a common early source of confusion, especially since two separately-created strings holding identical text often still fail an == check. The equals method, not ==, is what actually compares content.
The six comparison operators
==, !=, <, >, <=, >= each produce a boolean result.
Comparing primitives
For numbers, == and != check the actual numeric values directly.
Comparing objects
For anything that isn't a primitive, == and != compare references — are these the same object? — not content.
Comparing content instead
The equals method, inherited from Object and overridden by classes like String, is what actually compares content rather than identity.
Ordering only works on numbers and char
<, >, <=, >= are defined for numeric types and char, but not for objects like String, which need compareTo instead.
public class ComparisonDemo { public static void main(String[] args) { int a = 5, b = 10; String s1 = new String("hi"); String s2 = new String("hi"); System.out.println("a < b: " + (a < b)); System.out.println("s1 == s2: " + (s1 == s2)); System.out.println("s1.equals(s2): " + s1.equals(s2)); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.