Why do these two statements show different result?

Integer i1 = 127; Integer i2 = 127; // Statement 1 : true System.out.println(i1 == i2); i1 = 128; i2 = 128; // Statement 2 : false System.out.println(i1 == i2); https://code.sololearn.com/cqMfP6Czhd38/?ref=app

1/13/2020 1:01:58 AM


2 Answers

New Answer


Effect of an efficiency detail of the JVM. https://www.sololearn.com/discuss/2123471 Note that '==' does not compare values but references since you are using wrapper classes. So, the question is: are 'i1' and 'i2' referencing the same objects? Usually, they are not, hence the result 'false'. For low integer values [in the Byte range -128 .. 127], the JVM pools those objects. They infact exist only once. Thus, for Integer value 127, 'i1' and 'i2' DO reference the same object. Hence the result 'true'.


Jobelle As you already know the == operator always checks the reference or objects. So, whenever you create an object of Integer class(Wrapper class), the valueOf() method called every time. The value of the method checks the integer value if the value lies between -128 to 127 it returns the same reference. If value exceed from the limit then it creates a new object. You can check the code of the ValueOf() method in JDK. https://javagoal.com/integer-wrapper-object-interning/