• 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

how == works on Integer wrapper class

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
according to one question at javaranch round up game, following will return false :
Integer a = new Integer(5);
Integer b = new Integer(5);
if (a==b);

this if statement will return false according to java ranch but the correct answer is true as JVM keeps single object for Integer and Short within the range -128 to 127.

hence the result of this if should be true
 
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

hence the result of this if should be true



Try it... you'll see that it returns false.


... but the correct answer is true as JVM keeps single object for Integer and Short within the range -128 to 127.



There is no black magic going on here. If you instantiate two objects, you will have two objects. Java doesn't do anything at the compiler or JVM level to magically save object from being instantiated.

This "integer cache" for values "within the range -128 to 127" is implemented by the valueOf() method, which in turn is called by autoboxing. This example uses neither the valueOf() method or autoboxing.

Henry
 
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The modifier new ALWAYS creates a new instance, whether it's String, Integer, Short etc.

What you want to do is use Integer.valueOf(), this uses the internal cache.
 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It will return false as it refers to two different objects in memory. Like Henry mentioned using valueOf() will make the condition return true.
 
Marshal
Posts: 79178
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
And welcome to JavaRanch ( ) both of you.
 
reply
    Bookmark Topic Watch Topic
  • New Topic