Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Wrapper class

 
kish kumar
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi



The above code prints true and false . why this difference?
 
YogeshS Pandit
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you sure your code is compilable?
Float l1=30L;
This statement cannot be compiled. I think you wanted to say something like . There are two aspects to this question. When the autoboxing happens, the original code gets replaced to after compilation. Now if you see valueOf() implementation of non floating point numbers (i.e. Integer, Long etc), the object returned by valueOf() method can come from internal cache maintained by the class (e.g. java.lang.Long has a private static class LongCache which maintains cache of objects from values -128 to 127). This is done for performance sake. So, when you say , a Long object with value 30 will be created and inserted into the cache. And the next time you create Long object with same value (i.e. 30), the same object will be returned from cache. Note that returning same object for different references is perfectly safe as all wrapper classes are immutable. The same is not true with floating point wrapper classes for various reasons. Here is a code snippet from java.lang.Long class which returns wrapper object with given long value.

Another thing to note is, when you create long object greater than 127 or less than -127 and try to do the same, you will see that you have received two different objects for the same value. Correct me if I am wrong here.
 
kish kumar
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply ,

i saw the source code. For the Float and Double irrespective of the value a new object is created.

For the others wrapper objects caching is happening if they are between -128 to 127
 
YogeshS Pandit
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are welcome.
 
YogeshS Pandit
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One correction in my comment.
a Long object with value 30 will be created and inserted into the cache
This is a wrong statement. The caches of the wrapper classes are preloaded in a static block of the wrapper class. valueOf() doesnt insert an object in the cache. Apologies for the same.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic