Fundamentals 6 min read

Why Does Comparing Two Java Integer Objects Sometimes Return True?

This article explains why using the == operator on two Java Integer objects can yield true for values between -128 and 127 but false for larger numbers, detailing the Integer cache mechanism, reference vs value comparison, and the proper use of equals for value equality.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
Why Does Comparing Two Java Integer Objects Sometimes Return True?

Introduction

When comparing two Integer objects in Java, the result can be surprising.

Integer a = 100;
Integer b = 100;
System.out.println(a == b); // true

For values outside the cache range the same code prints false:

Integer a = 1000;
Integer b = 1000;
System.out.println(a == b); // false

1. Integer objects and the cache

Integer is the wrapper class for the primitive int. All non‑primitive types are objects that store references.

Java maintains an internal cache (IntegerCache) for the values -128 to 127. When an Integer is created within this range, the same cached object is returned; otherwise a new object is allocated.

Thus, for 100 the two variables reference the same cached object, while for 1000 they reference different objects.

2. Equality comparison

The == operator compares object references, so it returns false for two distinct Integer instances.

To compare the numeric values, use the equals method, which Integer overrides to compare the underlying int values.

Integer a = Integer.valueOf(1000);
Integer b = Integer.valueOf(1000);
System.out.println(a.equals(b)); // true

Summary

Use == to check if two references point to the same object.

Use equals to check if two Integer objects hold the same value.

The Integer cache covers -128 to 127, reducing memory usage for frequently used numbers.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaObject Comparisonintegerequals method
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.