This question already has an answer here:
Why Integer "=" operator does not work for 128 and after Integer values? Can someone explain this situation?
This is my Java environment: java version "1.6.0_37"
Java(TM) SE Runtime Environment (build 1.6.0_37-b06)
Java HotSpot(TM) 64-Bit Server VM (build 20.12-b01, mixed mode)
Sample Code:
Integer a;
Integer b;
a = 129;
b = 129;
for (int i = 0; i < 200; i++) {
a = i;
b = i;
if (a != b) {
System.out.println("Value:"+ i + " - Different values");
} else {
System.out.println("Value"+ i + " Same values");
}
}
Some part of console output :
Value:124 - Same values
Value:125 - Same values
Value:126 - Same values
Value:127 - Same values
Value:128 - Different values
Value:129 - Different values
Value:130 - Different values
Value:131 - Different values
Value:132 - Different values
Thanks!
Depending on how you get your
Integer
instances, it may not work for any value:prints
This is because the
==
operator applied to reference-typed operands has nothing to do with the value those operands represent.