Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Equality of Integers

 
Ganesha Kumar
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone explain this one for me:
public class SameObject {
public static void main(String args[]){
Integer i1=128;
Integer i2=128;
System.out.println(i1==i2);
}
}
The output will be false
Whereas
public class SameObject {
public static void main(String args[]){
Integer i1=18;
Integer i2=18;
System.out.println(i1==i2);
}
}
results in the output true
Why is this difference.
 
Ram Reddy
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If assigned value for intergers is between -128 to 127 , then compiler checks for the pool (already contained values) . if it finds assigns from it . other wise it creates new one.

so if integer value is -128 to 127 , then it assignes same value for both objects . so it returns "true"
 
Ganesha Kumar
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
But suppose if
Integer i1 =128;
int i2=128;
This would result in i1==i2 being true. This confuses me a bit
 
Gurpreet Bajaj
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i checked, the first one gives "true" too
 
Gurpreet Bajaj
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i checked 4 i1=i2=129 and i1=i2=2007, both give true
 
Wiyanto Ngasinur
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


this ones print false, since integer constant pool range -128 - 127

But suppose if
Integer i1 =128;
int i2=128;
This would result in i1==i2 being true. This confuses me a bit


this ones print true, because there is autoboxing. i1 is unboxing to int, then comparing primitive result true
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic