This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Object creation for Integer class

 
Satya Baswa
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 26
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Tarun Kumar
Greenhorn
Posts: 26
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 144
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Thanks!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic