Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

sierra/bates ch.4 self test, question #2 (Combination Autoboxing & (Non-)Equality Operator)

 
Wout Er
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Himai Minh
Ranch Hand
Posts: 1226
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe autoboxing only applies to boxing primitve value to its corresponding wrapper object or vice versa, but not to any other object type.
 
Wout Er
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Joe Allen
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd think it'd work if you cast o to Integer before doing a comparison.
System.out.println(((Integer)o) == 2);
System.out.println(((Integer)o) != 2);
 
Wout Er
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
joe alien wrote:I'd think it'd work if you cast o to Integer before doing a comparison.
System.out.println(((Integer)o) == 2);
System.out.println(((Integer)o) != 2);


That works indeed, but that's not my question.. For my question, 'o' can be any Object instance (not just wrapper-type instances).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic