In Java, the ==
operator checks for reference equality, meaning it compares whether the two variables point to the same object in memory.
The .equals()
method checks for value equality, meaning it compares the actual values of the objects.
Integer Caching in Java
Java caches Integer
objects for values in the range of -128 to 127 for performance reasons. When you use Integer
objects (not int
primitives) in this range, Java reuses the same object references, so comparisons using ==
will return true
.
Integer a = 1;
Integer b = 1;
System.out.println(a == b); // true, because both reference the same cached object
However, outside the cached range (e.g., for 128 and beyond), new Integer
objects are created, so the references are different.
Integer a = 128;
Integer b = 128;
System.out.println(a == b); // false, because a and b are different objects
Correct Comparison with .equals()
To compare the actual values of Integer objects, you should use .equals()
instead of ==
:
Integer a = 128;
Integer b = 128;
System.out.println(a.equals(b)); // true, because it compares values, not references
In summary:
- 1 == 1 works because both objects point to the same cached reference.
- 128 == 128 returns false because Java creates separate objects for values outside the caching range.
If youβre comparing values and not references, always use .equals() for non-primitive types like Integer.
Top comments (0)