Compare int and Object in Java

12,190

Solution 1

What's at play here is autoboxing.

When you use a primitive literal when a reference is expected, the primitive is autoboxed to the wrapper type (in this case from int to Integer).

Your code is the equivalent of this:

Object obj = Integer.valueOf(3);
if ( obj.equals(Integer.valueOf(3)) ) {
    //...

I'll leave it to you to decide whether that's true or not.

Solution 2

This is also interesting:

Object t = 3;

t.equals( 3 );  // true
3 == t;         // true 

But

Object h = 128; 

h.equals( 128 ); // true 
128 == h;        // false

.equals will work, becase the value will be compared. == Will work, using the references, but only from -128 to 127, because the autoboxing mechanism, uses an internal pool to hold "most commonly used" references.

Strange enough: o == 3 will fail at compile time.

Solution 3

Yes.

Here is what's happening behind the scenes.

Object obj = Integer.valueOf(3);
obj.equals(Integer.valueOf(3));

So, of course they are equal.

Solution 4

The first statement will set obj to be a automatically boxed Integer (the same as Integer.valueOf(3))

Hence the second statement will return true.

Share:
12,190

Related videos on Youtube

user
Author by

user

Updated on June 04, 2022

Comments

  • user
    user almost 2 years

    I have the following code:

    Object obj = 3;
    //obj.equals(3); // so is this true?
    

    Does obj equal to 3?

    • Mark Peters
      Mark Peters over 13 years
      What happened when you tried it?
    • user
      user over 13 years
      obj.equals(3) was true, but I'd like to know if it was only "luck" or it really equals to 3
    • Tony Ennis
      Tony Ennis over 13 years
      You're thinking along the right lines. Depending on luck sucks.
  • medloh
    medloh over 8 years
    o? Where is that declared?