System.out.println(i3==i4), why the output result is not true
class Demo
{
public static void main(String[] arge)
{
Integer i1=100;
Integer i2=100;
Integer i3=200;
Integer i4=200;
System.out.println(i1==i2);
System.out.println(i3==i4);
}
}
First of all, we know that the object type compares the memory address it refers to when doing ==. So in the original poster's demo, in principle, i1==i2 and i3==i4 compare the memory addresses they reference, which should both be false. However, Java introduced the Integer caching mechanism in Java5. When developers use the Integer type, if the defined value is between -128~127, the reference will be pointed directly to the created cache object.
In the poster’s demo, the two variables i1 and i2 are between -128~127, so the references of the two variables point to the same object instance (the same memory address), so true is returned, while the two variables i3 and i4 The value is not between -128~127, so the jvm creates new object instances (different memory addresses) for these two automatically boxed object types, so it returns false.
The maximum value of the Integer cache mechanism can be adjusted through the jvm parameter -XX:AutoBoxCacheMax=size. For details and principles of Integer, please refer to this blog. http://blog.csdn.net/u0110040...
The plastic wrapper class will cache integer objects from 0 to 150, so if it is less than 150, the cache will be used during boxing. 100 is an object in the cache, and 200 is a newly created object