aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Wrapper class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Wrapper class" Watch "Wrapper class" New topic
Author

Wrapper class

kish kumar
Ranch Hand

Joined: Jan 03, 2008
Posts: 54
Hi



The above code prints true and false . why this difference?
YogeshS Pandit
Greenhorn

Joined: May 10, 2010
Posts: 9
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

Joined: Jan 03, 2008
Posts: 54
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

Joined: May 10, 2010
Posts: 9
You are welcome.
YogeshS Pandit
Greenhorn

Joined: May 10, 2010
Posts: 9
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Wrapper class