Puzzling behaviour of == after postincrementation [duplicate]

别说谁变了你拦得住时间么 提交于 2019-12-05 03:36:22
Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1++ == i2++); 
// here i1 and i2 are still 127 as you expected thus true
System.out.println(i1 == i2); 
// here i1 and i2 are 128 which are equal but not cached
    (caching range is -128 to 127), 

In case 2 if you use equals() it'd return true as == operator for integers only works for cached values. as 128 is out of cache range the values above 128 will not be cached, thus youhave to use equals() method to check if two integer instances above 127 are true

TEST:

Integer i1 = 126;
    Integer i2 = 126;
    System.out.println(i1++ == i2++);// true
    System.out.println(i1 == i2); //true



 Integer i1 = 126;
        Integer i2 = 126;
        System.out.println(i1++ == i2++);// true
        System.out.println(i1.equals(i2)); //true

  Integer i1 = 128;
        Integer i2 = 128;
        System.out.println(i1++ == i2++);// false
        System.out.println(i1==i2); //false

  Integer i1 = 128;
        Integer i2 = 128;
        System.out.println(i1++.equals(i2++));// true
        System.out.println(i1.equals(i2)); //true

As explained this is due to Integer caching. For fun, you can run the program with the following JVM option:

-XX:AutoBoxCacheMax=128

and it will print true twice (option available on hostpot 7 - not necessarily on other JVMs).

Note that:

  • this is JVM specific
  • the modified behaviour is compliant with the JLS which says that all values between -128 and +127 must be cached but also says that other values may be cached.

Bottom line: the second print statement is undefined in Java and can print true or false depending on the JVM implementation and/or JVM options used.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!