arjacsoh
arjacsoh

Reputation: 9232

Compare Integer with primitive

I do not have a java compiler and I would like to check how treats java the comparison of Integer Objects with primitives. Can someone confirm that the results of the following comparisons are correct:

Integer a = 500;
long b = 500;
a == b  //-> false
a.equals(b)  //-> true

Is it generally true that in the first type of comparison java does Boxing and in the second Unboxing and compares primitive values?

Upvotes: 2

Views: 448

Answers (1)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136042

See my results

    Integer a = 500;
    long b = 500;
    System.out.println(a == b);
    System.out.println(a.equals(b));

output

true
false

this is because the first comparison uses unboxing

b == a.intValue()

which produces true, because in Java 500L == 500 is true.

The second comparison uses boxing

a.equals(Long.valueOf(b))

this produces false because a and b are instances of different classes. See Integer.equals impl:

public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

Upvotes: 7

Related Questions