Mind-blowing: Why 1 == 1 is 🟢 true, but 128 == 128 is 🔴 false in Java?

vsnikhilvs

Nikhil Vikraman

Posted on October 13, 2024

Mind-blowing: Why 1 == 1 is 🟢 true, but 128 == 128 is 🔴 false in Java?

In Java, the == operator checks for reference equality, meaning it compares whether the two variables point to the same object in memory.

The .equals() method checks for value equality, meaning it compares the actual values of the objects.

Integer Caching in Java

Java caches Integer objects for values in the range of -128 to 127 for performance reasons. When you use Integer objects (not int primitives) in this range, Java reuses the same object references, so comparisons using == will return true.

Integer a = 1;
Integer b = 1;
System.out.println(a == b);  // true, because both reference the same cached object
Enter fullscreen mode Exit fullscreen mode

However, outside the cached range (e.g., for 128 and beyond), new Integer objects are created, so the references are different.

Integer a = 128;
Integer b = 128;
System.out.println(a == b);  // false, because a and b are different objects
Enter fullscreen mode Exit fullscreen mode

Correct Comparison with .equals()

To compare the actual values of Integer objects, you should use .equals() instead of ==:

Integer a = 128;
Integer b = 128;
System.out.println(a.equals(b));  // true, because it compares values, not references
Enter fullscreen mode Exit fullscreen mode

In summary:

  • 1 == 1 works because both objects point to the same cached reference.
  • 128 == 128 returns false because Java creates separate objects for values outside the caching range.

If you’re comparing values and not references, always use .equals() for non-primitive types like Integer.

💖 💪 🙅 🚩
vsnikhilvs
Nikhil Vikraman

Posted on October 13, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related