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

Whizlabs question - Generics/Wrapper classes

 
Vyas Sanzgiri
Ranch Hand
Posts: 686
Chrome Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Henry Wong
author
Marshal
Pie
Posts: 21001
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Vyas Sanzgiri
Ranch Hand
Posts: 686
Chrome Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok!! Now I understand it is the pool concept as in String
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic