• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how does "less than" work but "equals" doesn't work

 
James Quinton
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
given:

Integer s1=1;
Short s2=2;
if(s1==s2){}

compiling fails by type mismatch.

but operator <=, <, > and >= all passed compiling, only == and != fail. what's the reason behind this?
it looks to me that == and != don't do unboxing, they just compare two objects directly and fail because type mismatch.
while <=, <, > and >= do auto-unboxing and compare the primitive type value.
Am I right?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because of the context of the use of == and !=. You can use == and != between object references, and it has a totally different meaning that when you use it with primitives.

In the case of > and <, there are no analogous operators for object references, so since the objects can be unboxed to primitive numerics, they are.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's all rather messy because 42 == Integer.valueOf(42); does work. The object is unboxed. It all means that you have to pay a greater deal of attention to any code involving these wrapper objects. Instead of compiler options like -source = 1.5 I wish they had done something like they did with assertions: -enable-boxing/-disable-boxing.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic