I have the following code:
Object obj = 3;
//obj.equals(3); // so is this true?
Does obj
equal to 3?
I have the following code:
Object obj = 3;
//obj.equals(3); // so is this true?
Does obj
equal to 3?
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.
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.
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.
This is also interesting:
Object t = 3;
t.equals( 3 ); // true
3 == o; // 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.