Why do these two statements show different result? | SoloLearn: Learn to code for FREE!

+6

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

Jobelle

1 Answer

New Answer

+5

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/