26

Walk with me ..

Integer x = 23;
Integer y = 23;

if (x == y)
    System.out.println("what else");      // All is well as expected
else
    System.out.println("...");

While

Integer x = someObject.getIndex();
Integer y = someOtherObject.getSomeOtherIndex();

if (x == y)
    System.out.println("what else");  
else
    System.out.println("...");        // Prints this 

Hmm ... I try casting to int

int x = someObject.getIndex();
int y = someOtherObject.getSomeOtherIndex()

if (x == y)       
    System.out.println("what else");   // works fine
else
    System.out.println("...");  

Are they both Integers?

System.out.println(x.getClass().getName());              // java.lang.Integer
System.out.println(y.getClass().getName());              // java.lang.Integer
System.out.println(someObject.getIndex());               // java.lang.Integer
System.out.println(someOtherObject.getSomeOtherIndex()); // java.lang.Integer

What do you guys think? What would explain something like this?

James Raitsev
  • 92,517
  • 154
  • 335
  • 470
  • possible duplicate of [How != operator and == operator works in Java?](http://stackoverflow.com/questions/9824053/how-operator-and-operator-works-in-java) – assylias Apr 03 '12 at 22:08
  • What do `getIndex();` and `getSomeOtherIndex()` do? – Ciro Santilli OurBigBook.com Feb 17 '16 at 12:08
  • Possible duplicate of [Why does 128==128 return false but 127==127 return true when converting to Integer wrappers?](https://stackoverflow.com/questions/1700081/why-does-128-128-return-false-but-127-127-return-true-when-converting-to-integ) – Tom Feb 05 '18 at 16:17

3 Answers3

45

You're comparing Integer values, which are references. You're coming up with those references via autoboxing. For some values (guaranteed for -128 to 127) the JRE maintains a cache of Integer objects. For higher values, it doesn't. From section 5.1.7 of the JLS:

If the value p being boxed is true, false, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise. The final clause above requires that certain common values always be boxed into indistinguishable objects. The implementation may cache these, lazily or eagerly. For other values, this formulation disallows any assumptions about the identity of the boxed values on the programmer's part. This would allow (but not require) sharing of some or all of these references.

This ensures that in most common cases, the behavior will be the desired one, without imposing an undue performance penalty, especially on small devices. Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.

Moral: don't compare Integer references when you're interested in the underlying int values. Use .equals() or get the int values first.

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
13

To compare the Integers correctly, you need to use .equals() or compare their primitive values by casting to int or calling intValue() on them.

Using == checks whether the two Integers are the same Object, not whether they contain the same numerical value.

    Integer a = new Integer(1);
    Integer b = new Integer(1);

    System.out.println(a.equals(b));                  //true
    System.out.println((int)a == (int)b);             //true
    System.out.println(a.intValue() == b.intValue()); //true
    System.out.println(a == b);                       //false

Edited to illustrate Jon's point from the JLS about autoboxing:

    Integer a = 1;
    Integer b = 1;
    System.out.println(a.equals(b));                  //true
    System.out.println((int)a == (int)b);             //true
    System.out.println(a.intValue() == b.intValue()); //true
    System.out.println(a == b);                       //true

versus:

    Integer a = 128;
    Integer b = 128;
    System.out.println(a.equals(b));                  //true
    System.out.println((int)a == (int)b);             //true
    System.out.println(a.intValue() == b.intValue()); //true
    System.out.println(a == b);                       //false
DNA
  • 42,007
  • 12
  • 107
  • 146
1

Sounds like something is funky with auto-boxing when you use == on the two integers.

I would assume that it works fine when using Integer if you use the equals() method? That would by my guess anyway.

You're not using java 1.4 or something are you?

Leigh
  • 28,765
  • 10
  • 55
  • 103
  • The other answers indicate exactly why this is happening: The JVM caches small values of Integers. So, when I compare (new Integer (12) == new Integer (12)) [yields true] the JVM returns the SAME cached object for both sides of that value of 12. So, indeed the objects are the same. For large values, independently new objects are created, and this does not happen. – ingyhere Dec 14 '13 at 19:25