Primitive Wrapper Class == comparison behaving strangely

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
Sweetpin2

Primitive Wrapper Class == comparison behaving strangely

Post 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

admin
Site Admin
Posts: 10066
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Primitive Wrapper Class == comparison behaving strangely

Post 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.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 205 guests