Why Does Comparing Two Integer Objects in Java Sometimes Return True?
This article explains why using the == operator on two Integer objects in Java can yield true for some values and false for others, covering Integer caching, the role of Integer.valueOf, and the correct way to compare Integer values with equals.
Introduction
When comparing two Integer objects in Java, the result can be surprising: small values may compare equal with ==, while larger values do not.
Integer a = 100;
Integer b = 100;
System.out.println(a == b); // true
Integer a = 1000;
Integer b = 1000;
System.out.println(a == b); // falseThe difference stems from how Java handles Integer objects internally.
1. Integer objects and caching
Integeris the wrapper class for the primitive int. Apart from the eight primitive types, all other types are objects that store references.
When an Integer is created via autoboxing or Integer.valueOf, Java first checks an internal cache called IntegerCache. Values in the range -128 to 127 are cached and the same object instance is returned.
For values outside this range, Integer.valueOf creates a new object on the heap, so each variable holds a distinct reference.
2. Equality comparison
The == operator compares object references. Therefore, two Integer variables that refer to different objects (e.g., values 1000) will return false.
Integer a = Integer.valueOf(1000);
Integer b = Integer.valueOf(1000);
System.out.println(a == b); // falseTo 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)); // trueThe overridden equals method internally calls intValue() and then uses == on the primitive values.
Summary
The Integer class caches objects for values between -128 and 127. Autoboxing and Integer.valueOf return cached instances for these values, making a == b true. For values outside the cache, new objects are created, so == compares references and returns false; use equals to compare the actual numeric values.
Use == to test whether two references point to the same object.
Use equals to test whether two Integer objects hold the same numeric value.
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.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
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.
