File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Whizlabs question - Generics/Wrapper classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Whizlabs question - Generics/Wrapper classes" Watch "Whizlabs question - Generics/Wrapper classes" New topic
Author

Whizlabs question - Generics/Wrapper classes

Vyas Sanzgiri
Ranch Hand

Joined: Jun 16, 2007
Posts: 686

In chapter 3 (K&B Java 5) Page 236 it says that in order to save memory 2 instances of following wrapper objects will always be == when their primitive values are the same: Boolean, Byte, Character from \u000 to \u007f, Short and Integer from -128 to 127. So why does the first comparison return false and second returns true.

I checked the classes and both return java.lang.Integer. Both return values 18 (within range).



Output:

class java.lang.Integer
class java.lang.Integer
false
true
they are equal


===Vyas Sanzgiri===
My Blog
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18763
    
  40

In chapter 3 (K&B Java 5) Page 236 it says that in order to save memory 2 instances of following wrapper objects will always be == when their primitive values are the same: Boolean, Byte, Character from \u000 to \u007f, Short and Integer from -128 to 127. So why does the first comparison return false and second returns true.


I think you may have taken the sentence out of context... This is only true if autoboxing (or the valueOf(int) method) is used. In your example, at line #1, you are *not* using autoboxing, so the instance is not the same instance that is used at line 2 (where autoboxing is used).

If both line #1 and line #2 used autoboxing, then the statement would be true.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Vyas Sanzgiri
Ranch Hand

Joined: Jun 16, 2007
Posts: 686

ok!! Now I understand it is the pool concept as in String
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Whizlabs question - Generics/Wrapper classes