Possible duplicate:Integer shell objects use the same instances only within 127?How do operators work? = and == for integers in Java?
I tried to compare two ints with the following cases and got unexpected results
when I did the following, @@@ was printed.
class C { static Integer a = 127; static Integer b = 127; public static void main(String args[]){ if(a==b){ System.out.println("@@@"); } } }
when I did the following, @@@ was not printed.
class C { static Integer a = 145; static Integer b = 145; public static void main(String args[]){ if(a==b){ System.out.println("@@@"); } } }
Can anyone tell me what could be the reason.
You are comparing object identifiers. For values below 128, the Integer class caches its objects. That is why in the first example it is equal. Another example is with higher values that are not cached.
@niklon, -128 .
VM arg -Djava.lang.Integer.IntegerCache.high=4711.
-Djava.lang.Integer.IntegerCache.high=4711
: http://vanillajava.blogspot.co.uk/2012/01/surprising-results-of-autoboxing.html
int s, . .equals int Object.
int
.equals
Object
Integer, int. , .equals(...) ==. , ==.
Integer
.equals(...)
==
, == , , .
if(a.equals(b)) == , Object.
if(a.equals(b))
== , int, long ..