aspose file tools*
The moose likes Beginning Java and the fly likes Integer Object Comparision Confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Integer Object Comparision Confusion" Watch "Integer Object Comparision Confusion" New topic
Author

Integer Object Comparision Confusion

panita lama
Greenhorn

Joined: Mar 18, 2010
Posts: 4
Can anyone please explain why the following piece of code is behaving in this manner

public class IntegerDemo {
public static void main(String args[]){
Integer num1=20;
Integer num2=20;
Integer num3=150;
Integer num4=150;

if(num1==num2){
System.out.println("num1 and num2 are equal");

}
else{
System.out.println("num1 and num2 are not equal");
}
if(num3==num4){
System.out.println("num3 and num4 are equal");
}
else{
System.out.println("num3 and num4 are not equal");
}

}
}


Output:
---------------
num1 and num2 are equal
num3 and num4 are not equal

Any help will be greatly appreciated.
Sridhar Santhanakrishnan
Ranch Hand

Joined: Mar 20, 2007
Posts: 317
IF the integer's value is between -128 to 127 then no new object is created and the same reference is returned. Thus, num1 and num2 are equal.
panita lama
Greenhorn

Joined: Mar 18, 2010
Posts: 4
Thanks a lot Sri
Sridhar Santhanakrishnan
Ranch Hand

Joined: Mar 20, 2007
Posts: 317
And Welcome to Javaranch
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3742
    
  16
Note that although the Java Language Specification requires the reuse of Integer objects in the range -128 to 127 as Sridhar explained, there is nothing to stop a JVM implementation from implementing the reuse of values outside this range as well. So , although in this case num3==num4 returned false, it is possible that in other JVMs it could return true i.e. you shouldn't write code that relies on num3==num4 returning false, where num3 and num4 are outside the range -128 to 127.


Joanne
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Integer Object Comparision Confusion