• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Small doubt in Boxing & == & equals()

 
Ranch Hand
Posts: 278
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Bartender
Posts: 6663
5
MyEclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
reply
    Bookmark Topic Watch Topic
  • New Topic