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.
Introduction
When comparing two Integer objects in Java, the result can be surprising.
Integer a = 100;
Integer b = 100;
System.out.println(a == b); // trueFor values outside the cache range the same code prints false:
Integer a = 1000;
Integer b = 1000;
System.out.println(a == b); // false1. 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)); // trueSummary
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
