Why Does 1 == 1
Return true
, but 128 == 128
Does Not in Java?
What is a Wrapper Class?
A wrapper class in Java is a class that wraps a primitive data type into an object. Java provides wrapper classes for all primitive types, allowing them to be treated as objects.
Common Wrapper Classes:
Primitive Type | Wrapper Class |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
Wrapper classes are useful when working with collections (List
, Set
, Map
) since these collections store objects rather than primitive types.
Comparing Primitive int
Values
When using ==
with primitive types (like int
), Java simply compares the actual values:
int a = 1;
int b = 1;
System.out.println(a == b); // true (compares values)
Since both a
and b
contain the same numeric value (1
), ==
returns true
.
Similarly:
int a = 128;
int b = 128;
System.out.println(a == b); // true (compares values)
Even for 128
, ==
still returns true
because int
does not involve wrapper classes and works purely based on values.
Comparing Integer
Wrapper Objects
When using Integer
(wrapper class), Java applies Integer Caching for values from -128
to 127
:
Integer x = 1;
Integer y = 1;
System.out.println(x == y); // true (cached object)
Since 1
lies within the cached range (-128
to 127
), Java reuses the same object. Therefore, ==
returns true
.
However:
Integer x = 128;
Integer y = 128;
System.out.println(x == y); // false (different objects)
Since 128
lies outside the cached range, Java creates new objects. Now ==
compares memory references, not values, so it returns false
.
Correct Way to Compare Integer
Values
To compare actual values (instead of memory references), always use .equals()
:
Integer x = 128;
Integer y = 128;
System.out.println(x.equals(y)); // true (compares values correctly)
The .equals()
method compares the underlying int
values, so it correctly returns true
.
Key Takeaways
int
comparison (==
) always works because it compares values.
Integer
uses caching for values -128
to 127
, so ==
works only within this range.
==
fails for Integer
values outside -128
to 127
because Java creates new objects for these values.
Always use .equals()
when comparing Integer
values to avoid unexpected results.
Pro Tip: If you must use ==
with Integer
, convert them to int
first using unboxing:
Integer x = 128;
Integer y = 128;
System.out.println(x.intValue() == y.intValue()); // true
This forces primitive comparison and gives the expected result.