Page 1 of 1

Primitive Wrapper Class == comparison behaving strangely

Posted: Thu Feb 07, 2013 9:41 pm
by Sweetpin2
Hi,

I am trying below code in IDE & getting strange response

Integer i1 = 100;
Integer i2 = 100;

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

It prints "same object". But as far as i know for wrapper class objects == compare's object refernce & hence should have gone to else part. The same code when code like below goes to else part

Integer i1 = 1000;
Integer i2 = 1000;

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

above code prints different objects

Re: Primitive Wrapper Class == comparison behaving strangely

Posted: Fri Feb 08, 2013 7:43 am
by admin
The automatically created wrapper objects (i.e. the ones that are created automatically without the use of new keyword as in your example above) for Integers between -128 to 127 are interned i.e. if the jvm sees that the same int is being used and then it returns the same Integer wrapper object. For 1000, interning does not happen and a different object is used.

HTH,
Paul.