File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Small doubt in  Boxing &  == &  equals() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Small doubt in  Boxing &  == &  equals()" Watch "Small doubt in  Boxing &  == &  equals()" New topic

Small doubt in Boxing & == & equals()

Lucky J Verma
Ranch Hand

Joined: Apr 11, 2007
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

Joined: Feb 24, 2006
Posts: 6662

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

SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
Lucky J Verma
Ranch Hand

Joined: Apr 11, 2007
Posts: 278
Actually my confusion is about == & !=
all the four variables i1 ,i2 ,i3 ,i4 have equal 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
I agree. Here's the link:
subject: Small doubt in Boxing & == & equals()
It's not a secret anymore!