Comparing objects and int in Java 7

I recently came across a question that made me stop and think ...

For me, the code below should always cause an error, but when one of my colleagues asked me why Eclipse did not show it, I could not answer anything.

class A { public static void main(String... args) { System.out.println(new Object() == 0); } } 

I researched and found that with an initial level of 1.6 it really throws an error:

 incomparable types: Object and int 

But now in 1.7 everything compiles fine.

Please, what new feature guarantees this behavior?

+15
java eclipse java-7 compare autoboxing
Aug 29 '13 at 0:00
source share
1 answer

What do you mean by the word "what new function justifies this behavior?" 1.7 fixes the problem contained in 1.6. new Object() == 0 should never have an error, but always triggered autoboxing.

There was simply no reason why

 Object a= 5 ; 

was right, not an expression

 a == 3 

or even

 a == 5 

It was extremely strange and, IMHO, contradicted the language specification itself.

However, from a dynamic point of view, a == 5 still evaluates to false , and (Integer)a == 5 or even (int)a == 5 evaluates to true . The reason is that autounboxing was designed to never ClassCastException and thus only occur for ClassCastException types, statically. In the later two cases, explicit casts are used, so a ClassCastException usually resolved.

+9
Aug 29 '13 at 0:05
source share



All Articles