EMZETT.
Login

Comparison Operators

In short: Operators that compare two values and always return a truth value (true/false) as the result — ==, !=, <, >, <=, >=.

In more detail: For primitive values, == compares the actual value; for reference types, by contrast, == in many languages only compares whether two variables refer to the same object in memory, not whether the objects are equal in content — a special comparison method is usually needed for that. Results of comparison operators are often directly combined further in if conditions or with logical operators.

In Depth

int a = 5, b = 5;
System.out.println(a == b);    // true - primitive values, direct comparison
 
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2);        // false! - two different objects in memory
System.out.println(s1.equals(s2));   // true - content comparison

This difference between == (reference equality for objects) and a content comparison method like .equals() is one of the most common pitfalls for beginners in languages like Java — two strings can contain exactly the same text and still count as ==-”unequal”, if they were created as two independent object instances. The rule of thumb: for objects (including strings), almost always use the dedicated comparison method, == only when you REALLY want to check whether it’s the same specific object.

For floating-point numbers (double/float), == is risky for a different reason: due to the limited precision of internal storage, a calculation that should mathematically give exactly 0.3 can actually return a tinily different value — a direct == comparison then unexpectedly fails. It’s common instead to check whether the difference between two floating-point numbers is smaller than a very small tolerance threshold.

Comparison operators always return exactly one truth value and can therefore be combined arbitrarily with logical operators, to form more complex conditions (age >= 18 && hasID).

See also: Operators, Logical Operators, if…else