aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Comparison between wrapper objects - weird behavior Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Comparison between wrapper objects - weird behavior" Watch "Comparison between wrapper objects - weird behavior" New topic
Author

Comparison between wrapper objects - weird behavior

Larry Olson
Ranch Hand

Joined: Feb 03, 2009
Posts: 142
(A) System.out.println(new Long(10) > new Integer(10));
(B) System.out.println(new Long(10) == new Integer(10));

(A) compiles and runs fine, whereas (B) fails to compile with the following error:
incomparable types: java.lang.Long and java.ang.Integer

When using "==", the compiler complains that the types aren't comparable, whereas it doesn't when using ">". How come? Why "==" can't compare when ">" can? I am at a total loss to understand this. Why would the java designers do this?

Of course I do know that == results in two references being compared to each other (and not the object state). Even in that case, shouldn't a == between two different wrapper object types be accepted by the compiler and result in a false, instead of resulting in a compiler error?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18138
    
  39

In the first case, it is obvious that the objects should be unboxed, as there is no way to compare if one object is greater than another object via the ">" operator. In the second case, it is not obvious that unboxing should be applied. So, it isn't, as autoboxing doesn't have priority over reference comparison.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Larry Olson
Ranch Hand

Joined: Feb 03, 2009
Posts: 142
Why isn't the compiler smart enough to figure out that the two objects being compared are wrapper objects for primitives and then unbox them and do the comparison? Why not? What will go wrong if we do that?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18138
    
  39

Compiler are written to specifications. And specifications are written to be very very specific -- sort of like legalese. There are no room for implementation details like do the "smart enough" thing.

Reference comparison is done when two objects are compared with the "==" operator, as per specification. Of course, you can always send a request to Sun Oracle to have the specification changed.

Henry
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Comparison between wrapper objects - weird behavior
 
Similar Threads
wrapper classes
using == operator on wrapper classes
mock question Wrapper issue
Wrapper Class Instantiation
var-args overloading compiler error: ambiguous