Bookmark Topic Watch Topic
  • New Topic

how is this possible please explain

 
Shashank Agarwalg
Ranch Hand
Posts: 110
Android Java Redhat
  • Mark post as helpful
  • send pies
  • Report post to moderator
Integer i1=1000;

Integer i2=1000;

if(i1!=i2) System.out.println("different objects");

if(i1.equals(i2)) System.out.println("meaningfully equal");


output

different objects //how is this possible please explain

meaningfully equal









b]Integer i3=10;

Integer i4=10;

if(i3==i4) System.out.println("same objects");

if(i3.equals(i4)) System.out.println("meaningfully equal");


output

same objects //how is this possible please explain

meaningfully equal


how if(i3==i4) and if(i1!=i2) both can be true
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Report post to moderator
When you initialize an Integer object using a literal value the auto-boxing mechanism uses Integer.valueOf() under the covers.
This method first checks a cache of Integer objects, which contains instances for primitive values -128 up to 127 by default.
If the primitive value passed to the valueOf() method lies within that range, a reference to the cached object is returned, otherwise a new Integer wrapper instance will be created (using the constructor).

In the case of you scenario the valueOf() call made by the auto-boxing mechanism will result in the creation of new Integer objects for i1 and i2, because the cache doesn't contain instance for that particular value. In case of i3 and i4 a cached Integer reference will be assigned. So i1 and i2 will refer to distinct Integer objects to which referential equality doesn't apply, whereas i3 and i4 will refer to the same object, to which referential equality does apply. If you are interested in "meanifull equivalency" you should use the equals() method to compare the Integer objects, and not the == or != operators.
 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Report post to moderator
Shashank:

This is possible because Integer has a cache of statically created objects. The minimum range is -128 - 127, but the actual range is based on where you get your libraries from.

John.
 
Rob Spoor
Sheriff
Pie
Posts: 20661
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Report post to moderator
Please Use One Thread Per Question. This question is the same as this one. Closing this thread.
 
    Bookmark Topic Watch Topic
  • New Topic