# Small doubt in Boxing & == & equals()

Lucky J Verma
Ranch Hand
Posts: 278
I could nt really understand this behavious of Integer references.
why == behaves differently for 2 sets.For i1 i2, i1!=i2 is true but for i3==i4 works.

{{Integer i1=1000;
Integer i2=1000;
if(i1!=i2) System.out.println("i1 are i2 are not same reference");
if(i1==i2) System.out.println("i1 & i2 are same refernce");
System.out.println(i1.equals(i2)+" "+(i1==i2)+" "+(i1!=i2));

Integer i3=1000;
Integer i4=1000;
if(i3==i4) System.out.println("i3 & i4 equal ");
if(i3!=i4) System.out.println("i3 and i4 not equals");

}

My output is-->
i1 are i2 are not same reference
true false true
i3 and i4 not equals

Deepak Bala
Bartender
Posts: 6663
5
You should have a look at the Integer pool and the difference between == and .equals() method. The == operator will only check if two references are pointing to the same location. The equals() check will check if two objects are meaningfully equal with respect to their contents. For example if 'pencil' and 'rubber' are two references of the same class type that point to the location LInteger@1234 then == will return true. If pencil.number and rubber.number are equals and if your equals method checks this, then pencil.equals(rubber) will return true

Lucky J Verma
Ranch Hand
Posts: 278
Actually my confusion is about == & !=
all the four variables i1 ,i2 ,i3 ,i4 have equal contents.so equals() is true.
for == ,means references ,for all are different but for 1 pair ,it says true ,for 1 is false.why that so.
K& B book ,Chap 3 pg 236 says,
---------------------------
in order to save memory ,if primitve value is same for two wrapper objects, it will be ==
---------------------------------

then program output should be true for both pairs, i1=i2 ,i3=i4.

thank you

 It is sorta covered in the JavaRanch Style Guide.