Why is 1==1 true but 128==128 false in Java? An analysis of integer caching using the Flyweight pattern
The article explains why comparing two Integer objects with == yields true for values within -128 to 127 but false for larger values, detailing Java's integer caching, the Flyweight pattern, and the proper use of equals() for value comparison.
Java's comparison behavior can be surprising: using == on primitive types compares values, while on object types it compares references. This leads to cases where 1 == 1 is true but 128 == 128 is false when the operands are Integer objects.
Primitive vs. Integer comparison
For primitive int values, 1 == 1 directly compares the two values and returns true. Integer is an object wrapper; using == on two Integer variables compares the object references, not the wrapped values.
Integer caching and the Flyweight pattern
Java applies an optimization based on the Flyweight design pattern: it caches Integer objects whose values are in the range -128 to 127. When an Integer is created via autoboxing within this range, the JVM returns the cached instance instead of allocating a new object.
Concrete examples
Integer a = 128;
Integer b = 128;
System.out.println(a == b); // false
Integer x = 1;
Integer y = 1;
System.out.println(x == y); // trueBecause 128 is outside the cache range, a and b refer to different objects, so a == b is false. Values 1 and -128 to 127 are cached, so x and y reference the same object, making
x == y true.
Correct way to compare Integer values
To compare the numeric values regardless of caching, use the equals() method:
Integer a = 128;
Integer b = 128;
System.out.println(a.equals(b)); // true, compares values equals()works for any Integer value, whether it is cached or not.
Key takeaways
For primitive types, == compares values.
For objects, == compares references.
Java caches Integer objects in the range -128 to 127 using the Flyweight pattern.
Use equals() to compare the numeric value of Integer objects safely.
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.
Programmer1970
Formerly called 'Code to 35'. Add our main WeChat ID to access a wealth of shared resources (algorithms, interview prep, tech stacks: Java, Python, Go, big data). We mainly share serious development techniques, focusing on output-driven input. Occasionally we post life snippets and gossip. Our aim is to attract precise traffic and test advertising opportunities.
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.
