user
user

Reputation: 6797

Compare int and Object in Java

I have the following code:

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

Does obj equal to 3?

Upvotes: 2

Views: 14835

Answers (5)

OscarRyz
OscarRyz

Reputation: 199215

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.

Upvotes: 4

parag.rane
parag.rane

Reputation: 137

You need to do Type-casting here to achieve the task


         Object obj = 3;
         if(obj.equals(Integer.valueOf(3)))
         {
        // to do something....  
         } 

Upvotes: 0

jjnguy
jjnguy

Reputation: 138864

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.

Upvotes: 3

mikera
mikera

Reputation: 106351

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.

Upvotes: 1

Mark Peters
Mark Peters

Reputation: 81074

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.

Upvotes: 9

Related Questions