Integer objects are objects. This sounds logical, but is the answer to the question. Objects are made in Java using the new
keyword, and then stored in the memory. When comparing, you compare the memory locations of the objects, not the value/properties of the objects.
Using the .equals()
method, you actually compare the values/properties of objects, not their location in memory:
new Integer(1) == new Integer(1)
returns false
, while new Integer(1).equals(new Integer(1))
returns true
.
int
s are a primitive type of java. When you create an int, all that is referenced is the value. When you compare any primitive type in Java, all that is compared is the value, not the memory location. That is why 5 == 5
always returns true.
When you compare an Integer
object to a primitive type, the object is cast to the primitive type, if possible. With an Integer
and an int
this is possible, so they are compared. That is why Integer(1).equals(1)
returns true.