Why in Java, when assigning variables i3, i4 with the same data type, System.out.println(i3==i4), the final output is not equal?
黄舟
黄舟 2017-06-28 09:24:50
0
2
1044

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);
}
}

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
迷茫

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!