Java – when comparing two equal integers in a while loop, does the equal operator fail?
I post two examples below
Example 1:
Integer myVar1 = 42985; Integer myVar2 = 1; while (true) { if (myVar2 == myVar1) { break; } ++ myVar2; }
Example 2:
Integer myVar1 = 42985; Integer myVar2 = 1; while (true) { if (myVar2 >= myVar1) { break; } ++ myVar2; }
Editor: Thank you for the good news! I now fully understand this problem. This new information explains some strange behaviors I encounter in my application I hope I can choose more than one best answer
Solution
This is one of the unpleasant effects of automatic boxing
In the first example, the = = operator indicates identity Equality: if two objects are the same instance, they will be equal
In the second example, the '> =' operator represents a numeric comparison: the two objects are automatically unboxed and then compared
To make things more confusing, there is a series of "small" integers (- 128 < = x < = 127, IIRC) JVM caches integer values, so the = = operator sometimes works Bottom line: use Equals() and compareTo().