Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Object and int in Java 7

I recently stumbled on a question that made me stop and think...

To me, the code below should always trigger an error, but when one of my colleagues asked me why Eclipse didn't show one, I couldn't answer anything.

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

I've investigated and found that with source level 1.6 it indeed throws an error:

incomparable types: Object and int

But now in 1.7 it compiles ok.

Please, what new feature does warrant this behavior?

like image 506
rsalmei Avatar asked Aug 29 '13 00:08

rsalmei


1 Answers

What do you mean by "what new feature does warrant this behavior?" ? 1.7 is fixing an issue present in 1.6. new Object() == 0 should have never produced an error, and always caused autoboxing to trigger.

There was simply no reason why

Object a= 5 ;

was correct, and not the expression

a == 3

or even

a == 5

It was extremely weird and, IMHO, contradictory with the language specification itself.

From a dynamic point of view, though, a == 5 still evaluates to false while (Integer)a == 5 or even (int)a == 5 evaluate to true. Reason is that autounboxing was designed to never produce ClassCastExceptions and thus occur for wrapper types only, statically. The later two cases are explicit casts so ClassCastExceptions are generally allowed.

like image 119
Mario Rossi Avatar answered Oct 11 '22 06:10

Mario Rossi