This question already has an answer here:
Why Integer "=" operator does not work for 128 and after Integer values? Can someone explain this situation?
This is my Java environment: java version "1.6.0_37"
Java(TM) SE Runtime Environment (build 1.6.0_37-b06)
Java HotSpot(TM) 64-Bit Server VM (build 20.12-b01, mixed mode)
Sample Code:
Integer a;
Integer b;
a = 129;
b = 129;
for (int i = 0; i < 200; i++) {
a = i;
b = i;
if (a != b) {
System.out.println("Value:"+ i + " - Different values");
} else {
System.out.println("Value"+ i + " Same values");
}
}
Some part of console output :
Value:124 - Same values
Value:125 - Same values
Value:126 - Same values
Value:127 - Same values
Value:128 - Different values
Value:129 - Different values
Value:130 - Different values
Value:131 - Different values
Value:132 - Different values
Thanks!
The Integer object has an internal cache mechanism:
Also see valueOf method:
This is why you should use
valueOf
instead ofnew Integer
. Autoboxing uses this cache.Also see this post: https://effective-java.com/2010/01/java-performance-tuning-with-maximizing-integer-valueofint/
Using
==
is not a good idea, use equals to compare the values.Check out the source code of Integer . You can see the caching of values there.
The caching happens only if you use
Integer.valueOf(int)
, not if you usenew Integer(int)
. The autoboxing used by you usesInteger.valueOf
According to the JLS, you can always count on the fact that for values between -128 and 127, you get the identical Integer objects after autoboxing, and on some implementations you might get identical objects even for higher values.
Actually in Java 7 (and I think in newer versions of Java 6), the implementation of the IntegerCache class has changed, and the upper bound is no longer hardcoded, but it is configurable via the property "java.lang.Integer.IntegerCache.high", so if you run your program with the VM parameter
-Djava.lang.Integer.IntegerCache.high=1000
, you get "Same values" for all values.But the JLS still guarantees it only until 127:
It's because
Integer
class implementation logic. It has prepared objects for numbers till 128. You can checkout http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Integer.java source of open-jdk for example (search for cache[]).Basically objects shouldn't be compared using
==
at all, with one exception to Enums.According to Java Language Specifications:
JLS Boxing Conversions
Refer to this article for more information on int caching
Integer
is a wrapper class forint
.Integer != Integer
compares the actual object reference, whereint != int
will compare the values.As already stated, values -128 to 127 are cached, so the same objects are returned for those.
If outside that range, separate objects will be created so the reference will be different.
To fix it:
int
orint
or.equals()
Use
.equals()
instead of==
.Integer values are only cached for numbers between -127 and 128, because they are used most often.