• Post Reply Bookmark Topic Watch Topic
  • New Topic

Comparison of 2 Integer values with "=="  RSS feed

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1.
{
Integer i1=127;
Integer i2=127;

System.out.println(i1==i2);
}
output:true




2.
{
Integer i1=129;
Integer i2=129;

System.out.println(i1==i2);
}
output:false



Why is the output of "1." and "2." different even if the difference is only in the values.
 
Ranch Hand
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When comparing objects like the Integer class, you have to you the equals(Object other) to compare their values. '==' will only compare the references of the objects, not their values.

Hunter
 
Ranch Hand
Posts: 59
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You get a difference in output because the operator == behaves differently for Integer/Short objects (created through auto-boxing) initialized with literal values in the range of -128 to +127. This is done to save memory.





 
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason is caching of values between -128 and 127 in combination with autoboxing. If you SearchFirst you'll find a few threads with more detailed explanations.
 
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I like this topic about the same problem.
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually it says in the Java™ Language Specification that at least the range -128..+127 must be cached. It also says it is preferable for larger ranges to be cached. So the behaviour of == for Integer objects might change from JVM to JVM and might be different next year from this year.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!