aspose file tools*
The moose likes Beginning Java and the fly likes how == works on Integer wrapper class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how == works on Integer wrapper class" Watch "how == works on Integer wrapper class" New topic
Author

how == works on Integer wrapper class

sumit S ahuja
Greenhorn

Joined: Sep 08, 2009
Posts: 2
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
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183
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.


JDBCSupport - An easy to use, light-weight JDBC framework -
Jaydeep Vaishnav
Greenhorn

Joined: Sep 08, 2009
Posts: 16
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

Joined: Oct 13, 2005
Posts: 39436
    
  28
And welcome to JavaRanch ( ) both of you.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how == works on Integer wrapper class