public class TestMe{
public static void main(String[] args) {
Integer i = 128;
Integer j = 128;
Integer k = 12;
Integer l = 12;
System.out.println(i == j);
System.out.println(k == l);
}
}
I'm getting the output: false true
Why is the 1st one false and 2nd one true?
See: http://javapapers.com/java/java-integer-cache/
Short answer:
In Java 5, a new feature was introduced to save the memory and improve performance for Integer type objects handlings. Integer objects are cached internally and reused via the same referenced objects.
This is applicable for Integer values in range between –127 to +127.
This Integer caching works only on autoboxing. Integer objects will not be cached when they are built using the constructor.
Integer values between -128 and 127 are cached for Integer.valueOf(...) methods which are often used by many operators, auto boxing and are called by compiler behind the scenes. You can increase this cached range by VM option -XX:AutoBoxCacheMax=size.
Your lines:
Integer k = 12;
Integer l = 12;
Are actually translated by compiler into:
Integer k = Integer.valueOf(12);
Integer l = Integer.valueOf(12);
That's why k and l instances have exactly one mutual Integer reference to the cached instance. This principle is also applicable to other wrapper classes.
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