• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

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: 23959
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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic