Why 1 == 1 is true and 1000 == 1000 is not equal in java ?
Someone recently asked me, this question and i was remembering the limits but the object referencing and object creating above the Integer limits slip out of my mind.. and i said true for both !!
because the answer for 1 == 1 is true and for 1000 == 1000 is false.
Let’s understand why..
When working with Java, you might encounter some surprising behavior when comparing Integer objects with the ==operator. Let’s explore why this happens and how autoboxing and Integer caching play a key role.
🔹 What is Autoboxing?
Autoboxing is the automatic conversion that the Java compiler performs between primitive types and their corresponding wrapper classes.
- Boxing: Converting a primitive → wrapper object
- Unboxing: Converting a wrapper object → primitive
Example:
int x = 10;
Integer y = x; // autoboxing (int → Integer)
Integer z = 20;
int w = z; // unboxing (Integer → int)Behind the scenes, the compiler rewrites this as:
Integer y = Integer.valueOf(x);
int w = z.intValue();🔹 Integer Caching in Java
To optimize memory usage, Java maintains a cache of Integer objects for values in the range -128 to 127. When you autobox a primitive in this range, Java reuses the same object reference instead of creating a new one.
- Values in range
[-128, 127]→ cached, same object reference. - Values outside range → new object each time.
🔹 Example Code
public class Main {
public static void main(String[] args) {
Integer a = 1000;
Integer b = 1000;
Integer c = 1;
Integer d = 1;
if (a == b) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
if (c == d) {
System.out.println("Match Found");
} else {
System.out.println("Match not found");
}
}
}Output:
Match not found
Match Found🔹 Why This Output?
- For
a = 1000andb = 1000:
1000is outside the cache range.Integer.valueOf(1000)creates new objects.aandbpoint to different references →==is false.
2. For c = 1 and d = 1:
1is inside the cache range.- Both point to the same cached object.
c == dis true.
🔹 Best Practice
The == operator checks object references, not values. To compare values of wrapper objects, always use .equals():
if (a.equals(b)) {
System.out.println("Match found");
}This way, your code will behave as expected regardless of caching.
Get Nadeemakhtar’s stories in your inbox
Join Medium for free to get updates from this writer.
🔹 Visualizing Integer Caching
Imagine Java’s memory as two sections:
- Cache: Stores
Integerobjects from -128 to 127. - New Objects: Created for values outside this range.
So:
Integer.valueOf(1)→ returns cached object.Integer.valueOf(1000)→ creates new objects every time.
✅ Key Takeaways
- Autoboxing automatically converts primitives ↔ wrappers.
- Java caches
Integerobjects in the range[-128, 127]. ==compares references,.equals()compares values.- Always use
.equals()when comparing wrapper objects.









