2

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?

3
  • It's very easy to get a JDK, an Eclipse installation and test this. But then, there's this! Commented Nov 29, 2013 at 8:12
  • Ok, thanks, really helpful. Unfortunately I have no possibility to test it with a real JDK in the next hours because of installation priviledges. Commented Nov 29, 2013 at 8:23
  • You can use that website (Compile and Execute Java online) which I linked in my previous comment. It runs right on your browser (well, the Java program runs on their servers). There's no need to install anything, even JRE. Commented Nov 29, 2013 at 8:25

1 Answer 1

7

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.