+ 1
Why the output is True False for the following code
Integer i1 = 127; Integer i2 = 127; System.out.println(i1 == i2); i1 = 128; i2 = 128; System.out.println(i1 == i2);
4 Respuestas
+ 5
Basically, it is an optimization to save memory.
On your IDE inside Integer class see IntegerCache static nested class, there you will find how is this implemented.
Here you will find detailed explanations:
https://stackoverflow.com/questions/3131136/integers-caching-in-java
https://dzone.com/articles/java-integer-cache-why-integervalueof127-integerva
https://stackoverflow.com/questions/20897020/why-integer-class-caching-values-in-the-range-128-to-127
+ 1
Thankyou voja
+ 1
Warning: A pure speculation.
It seems when <i1> and <i2> are assigned a new value, a new object is created for each these variables, and then, having each their own object, the == operator returns False. Because the variables <i1> and <i2> no longer reference to the same object.
System.identityHashCode(i1) differs to System.identityHashCode(i2). After the new value assignment.
However, I read in below discussion, System.identityHashCode() isn't something we should rely on for comparison of objects. This is not something comparable to the `address of` & operator in C/C++ I suppose.
https://stackoverflow.com/a/1961150
Hth, cmiiw
+ 1
so compare it with
i1.equals(i2)