File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes how does Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "how does "less than" work but "equals" doesn Watch "how does "less than" work but "equals" doesn New topic

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

James Quinton
Ranch Hand

Joined: Oct 02, 2006
Posts: 94

Integer s1=1;
Short s2=2;

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

Joined: Feb 07, 2005
Posts: 2398
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

Joined: Aug 03, 2002
Posts: 7729
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.

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
I agree. Here's the link:
subject: how does "less than" work but "equals" doesn't work
It's not a secret anymore!