Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how == works on Integer wrapper class

 
sumit S ahuja
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • 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
 
Henry Wong
author
Marshal
Pie
Posts: 21212
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • 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
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • 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.
 
Jaydeep Vaishnav
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • 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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49447
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to JavaRanch ( ) both of you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic