• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Integer Object Comparision Confusion  RSS feed

 
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.
 
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
 
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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!