6

Please can you explain the below behaviour.

public class EqAndRef {

    public static void main(String[] args) {
        Integer i = 10;
        Integer j = 10;

        Double a = 10D;
        Double b = 10D;

        System.out.println(i.equals(j));
        System.out.println(i == j);


        System.out.println(a.equals(b));
        System.out.println(a == b);


    }
}

Output on jdk 6

true
true
true
false

why a==b is false and i==j not false?

gregwhitaker
  • 13,124
  • 7
  • 69
  • 78
RKP
  • 99
  • 6
  • 1
    It's reference equality instead of value equality, with the `Integer` the constant was intern(ed) with the `Double` it wasn't. You should always prefer `.equals()` with `Object` types. – Elliott Frisch Sep 28 '14 at 02:28
  • 2
    See [Is it ok to compare immutable objects in Java using == instead of equals](http://stackoverflow.com/questions/10970823/is-it-ok-to-compare-immutable-objects-in-java-using-instead-of-equals) – Volune Sep 28 '14 at 02:29
  • @Volune, The Double objects in the example are immutable. – Solomon Slow Sep 28 '14 at 02:32
  • [java: Integer equals vs. ==](http://stackoverflow.com/questions/3637936/java-integer-equals-vs) – Pshemo Sep 28 '14 at 02:43

2 Answers2

19

The Integers i and j are constructed (via auto boxing) from integer literals from the range –128 to 127 and thus are guaranteed to be pooled by the JVM so the same object (see flyweight pattern) is used for them. Hence, they compare identical by object references.

For the Doubles a and b on the other hand, no such pooling guarantee exists and, in your case, you got two different objects that did not compare identical.

Using == to compare objects if you don't mean to check identity is to be considered suspect and should be avoided. The equals methods of both types are overridden to compare the boxed values (as opposed to object identity) which is why they return true in both cases (and should be used).

5gon12eder
  • 24,280
  • 5
  • 45
  • 92
2

Initialize the Integers the following way then you will get the difference as @5gon12eder said

The Integer s i and j are constructed (via auto boxing) from integer literals from the range –128 to 127 which are guaranteed to be pooled by the JVM so the same object (see flyweight pattern ) is used for them. Hence, they compare equal by object references.

try this code to initialize your integers

    Integer i = new Integer(10);
    Integer j = new Integer(10);
Muhammad
  • 6,725
  • 5
  • 47
  • 54