wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Equality of Integers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Equality of Integers" Watch "Equality of Integers" New topic
Author

Equality of Integers

Ganesha Kumar
Ranch Hand

Joined: May 04, 2006
Posts: 56
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

Joined: Feb 20, 2007
Posts: 88
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

Joined: May 04, 2006
Posts: 56
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

Joined: Mar 21, 2007
Posts: 3
i checked, the first one gives "true" too
Gurpreet Bajaj
Greenhorn

Joined: Mar 21, 2007
Posts: 3
i checked 4 i1=i2=129 and i1=i2=2007, both give true
Wiyanto Ngasinur
Ranch Hand

Joined: Dec 11, 2006
Posts: 34


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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Equality of Integers