File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Object creation for Integer class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Barcodes with iOS this week in the iOS forum
or Core Java for the Impatient in the Java 8 forum!

JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Object creation for Integer class" Watch "Object creation for Integer class" New topic

Object creation for Integer class

Satya Baswa

Joined: May 06, 2008
Posts: 3
1. Integer i1=new Integer(127);
2. Integer i2=new Integer(127);

Here only one object is being created. If the parameter value is greater 127 it creates two objects though the values passed are same. Why it is so?
Tarun Kumar

Joined: Apr 30, 2008
Posts: 26
this is beacause from 1 to 127 values are stored somewhere in cash (you can think it like as string constant pool.)
So once if a Integer object ranging from 1 to 127 is careted ,then when another object of same value needs to be created it will give the reference of the old object.

Tarun Kumar
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14589

No - two objects are created here.

Indeed, class Integer has a caching mechanism, but this only works when you're getting Integer objects by calling Integer.valueOf(...), or by autoboxing a primitive int into an Integer (by doing this, Integer.valueOf(...) is implicitly called).

If you create new Integer objects explicitly, then two new Integer objects are created.

If you would do this:

1. Integer i1 = 127;
2. Integer i2 = 127;

Then i1 and i2 would both refer to the same Integer object.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Tarun Kumar

Joined: Apr 30, 2008
Posts: 26
Mr Jasper is right,
As here new is being used to create the Integer object,hence whatever is the value(1-127 or higher) always a new obkect will be created.
Jart Bo
Ranch Hand

Joined: Oct 22, 2007
Posts: 144
Hi Jesper,

I haven't really done a deeper study on Wrappers except for the ones discussed in the KB book. I have learned that wrappers are immutable though. Is the concept of immutability of Wrappers the same concept with that of Strings?


I agree. Here's the link:
subject: Object creation for Integer class