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
posted
0
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
posted
0
Thanks a lot Sri
Sridhar Santhanakrishnan
Ranch Hand
Joined: Mar 20, 2007
Posts: 317
posted
0
And Welcome to Javaranch
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
9
posted
0
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.