-1

I was writing some test code and found one strange thing, and still confused how this is happening?

Integer i1 = 220;
Integer i2 = 220;

System.out.println(i1 == i2);

prints false as expected. But

Integer i1 = 20;
Integer i2 = 20;

System.out.println(i1 == i2);

prints true, but both are different references referring to different objects (I assume that).

How come second snippet prints true?

codingenious
  • 8,385
  • 12
  • 60
  • 90

1 Answers1

2

The == operator only works for Integer values between -128 and 127. That is why it doesn't work for 220 but does for 20. In general it is best to always use .equals() when comparing Integers and you should never rely on the == operator.

More information can be found here: https://www.owasp.org/index.php/Java_gotchas#Immutable_Objects_.2F_Wrapper_Class_Caching

Akshay
  • 814
  • 6
  • 19