I am new to java. I know somewhat about the wrapper classes and primitive datatypes, but what I have come across is surprising. On changing the values of the variables i and j from 1000 to 100, the output changes from false to true. I need to know the mechanism behind this.
class Demo{
public static void main(String[] args){
Integer i=1000,j=1000;
if(i==j)
System.out.println("true");
else
System.out.println("false");
}
}
the above code gives me "false" while..
class Demo{
public static void main(String[] args){
Integer i=100,j=100;
if(i==j)
System.out.println("true");
else
System.out.println("false");
}
}
the above code give me "true"
Integer has internal cache for values ranging from -128 to 127.
So for numbers within this range, the same instance of Integer is returned. == compares by instance, and so the same instance is used for 100.
Source JDK 1.6:
public static Integer valueOf(int i) {
final int offset = 128;
if (i >= -128 && i <= 127) { // must cache
return IntegerCache.cache[i + offset];
}
return new Integer(i);
}
Caching in wrapper classes Java
The purpose is mainly to save memory, which also leads to faster code due to better cache efficiency.
.equals when comparing value, not identityIf you are comparing two Integers, you should use i.equals(j) just like you would do to correctly compare the value of Strings. Also keep in mind that any operation which will unbox an Integer places an implicit call to Integer.intValue(), so remember to make these calls carefully, knowing when your Integer might be null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With