DEV Community

Cover image for Mind-blowing: Why 1 == 1 is 🟢 true, but 128 == 128 is 🔴 false in Java?
Nikhil Vikraman
Nikhil Vikraman

Posted on

5

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay