0

I found an interesting fact, but I don't know how it happened.

Integer x = 10;
Integer y = 10;
System.out.print(x==y);    // true
Integer x = 128;
Integer y = 128;
System.out.print(x==y);    // false
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Andyjun
  • 3
  • 3
  • You need to use `.equals()` here. See [this question](http://stackoverflow.com/questions/2772763/why-equals-method-when-we-have-operator); `==` and `.equals()` behave differently. – Pokechu22 Oct 18 '14 at 22:18

1 Answers1

0

Integer comparison using == works only for numbers between -128 and 127.

Because Integer is an Object, use equals that will work for all values.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
  • Actually it works for all Integers where you want to test Object identity. When you create a Integer object with valueOf() or by boxing you get cached singletons for Integers in the range -128…127 (but this is configurable) https://stackoverflow.com/a/15052272 – eckes Dec 13 '17 at 02:08