• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Whizlabs question - Generics/Wrapper classes

 
Ranch Hand
Posts: 686
Netbeans IDE Chrome Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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

 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Netbeans IDE Chrome Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
ok!! Now I understand it is the pool concept as in String
 
eat bricks! HA! And here's another one! And a tiny ad!
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic