Search code examples
javaandroidbreakcomparison-operators

When comparing two equal integers in while loop, the equal-to operator fails?


I've posted two examples below.

In the first example, I use the equal-to operator and the while process continues forever instead of breaking when it should.

In the second example, I use the greater-than-or-equal-to operator, and the process breaks when it should.

How is this even possible?

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;
  }

EDIT: Thank you everyone for the great answers! I fully understand the problem now and this new information explained several strange behaviors that I've encountered in my apps. I wish I could choose more than one best answer.


Solution

  • This is one of the less pleasant effects of auto-boxing.

    In your first example, the == operator indicates identity equality: the two objects will only be equal if they are the same instance.

    In your second example, the '>=' operator indicates numeric comparison: the two objects will be auto-unboxed and then compared.

    Making things more confusing, there's a range of "small" integers (-128 <= X <= 127, iirc) for which the JVM caches Integer values, so the == operator sometimes works.

    Bottom line: use .equals() and .compareTo().