The following compiles because the Long is unboxed and primitive comparison is used.
However, reading this, I was wondering whether autoboxing is ever used with the equality and non-equality operators (i.e., to obtain two object reference variables)?
The following does NOT compile due to incompatible types so apparently at least in this case, autoboxing is not used:
Thinking about it, it would make sense never to do autoboxing for the equality operator, since autoboxing typically implies a new object being created. Consequently, this new object will never be equal to another one that existed before the autoboxing took place.
I believe autoboxing only applies to boxing primitve value to its corresponding wrapper object or vice versa, but not to any other object type.
Joined: Nov 26, 2012
Himai Minh wrote:I believe autoboxing only applies to boxing primitve value to its corresponding wrapper object or vice versa, but not to any other object type.
Maybe I didn't make myself clear enough. The equals (==) operator, in general, works on either 2 primitives, or 2 object references. If you use it with a primitive and a wrapper object, the wrapper object is auto-unboxed and the primitive version of the operator is employed. In my example, I used the equals operator with a primitive and an Object instance, and the primitive was not auto-boxed for comparison.
My question is whether a primitive will ever be auto-boxed when you pass it as an argument to an equality or a non-equality operator while the other argument to the operator is an object reference?