I am comparing 2 pieces of code. First
Integer i=3;
Integer j=3;
if(i==j)
System.out.println("i==j"); //prints i==j
Second,
Integer i=3;
Integer j=new Integer(3);
if(i==j)
System.out.println("i==j"); // does not print
I have doubt that in the first snippet why i==j
is being printed? Shouldn't the references be different?
Because in the second peice of code your first integer is being auto-boxed while the second is not.
This means a new Integer instance is being created on the fly. These 2 object instances are different. The equality check will return false there as the two instances are actually different pieces of memory.
In a similar fashion to strings, when autoboxing is used, such as in
Java can draw from a pool of prefabricated objects. In the case of
j
, there's already anInteger
instance representing the value of3
in the pool, so it draws from that. Thus,i
andj
point to the same thing, thusi == j
.In your second example, you're explicitly instantiating a new
Integer
object forj
, soi
andj
point to different objects, thusi != j
.Because,
are internally using Integer#valueOf() to perform
autoBoxing
. And oracle doc says aboutvalueOf()
method that:Since the value
3
is cached therefore, both variablesi
andj
are referencing the same object. So,i==j
is returningtrue
.Integer#valueOf()
uses flyweight pattern.