Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparing Integer and Long

 
Boleh Boleh
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone explain to me how logical operators work on Integer and Long objects?


BUT



ALL compile ok, and give the right result. So why is equality "==" incomparable, but >, <, >=, <= are comparable?


 
Henry Wong
author
Marshal
Pie
Posts: 21216
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ALL compile ok, and give the right result. So why is equality "==" incomparable, but >, <, >=, <= are comparable?


When you compare with the == operator, the compiler is assuming that you are trying to compare whether the references are pointing to the same instance. And since there is no way that a Long reference can point to something that is pointed to by an Integer reference, and vice versa, it generates a compile error.

When you compare with the other operators, the compiler is assuming that you are trying to compare the values, as there is no way to compare references in that regard. And the objects are unboxed and then compared.

Henry
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic