• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Integer Object Comparision Confusion

 
panita lama
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Sri
 
Sridhar Santhanakrishnan
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And Welcome to Javaranch
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic