aspose file tools*
The moose likes Java in General and the fly likes how is this possible please explain Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply locked New topic
Author

how is this possible please explain

Shashank Agarwalg
Ranch Hand

Joined: Mar 03, 2010
Posts: 110

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


Trying to win the world.....................
SCJP 6.0 , SCWCD/OCPJWCD 5, BlackBerry Developer
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1763
    
    7

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.


Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
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

Joined: Oct 27, 2005
Posts: 19693
    
  20

Please Use One Thread Per Question. This question is the same as this one. Closing this thread.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how is this possible please explain