(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?
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.
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?