Understanding == operator for Object Comparison in Java

It is specified that comparing reference types which cannot be converted between them must result in a compile error. See the JLS chapter 15.21.3:

15.21.3. Reference Equality Operators == and !=

[...]

It is a compile-time error if it is impossible to convert the type of either operand to the type of the other by a casting conversion (§5.5). The run-time values of the two operands would necessarily be unequal (ignoring the case where both values are null).


Although it has been answered beautifully by @Progman, I want to put it in another perspective.

Thread extends Object , Hence it is valid to say Object o = new Thread() Now String extends Object , but String does not extends Thread hence String iDoNotComplie = new Thread() is not valid.

Now If we have Thread t = new Thread() then If we have a reference of type Object , o and another reference of type String, s then it may be that o is actually referring to an object of Thread but it is impossible for s to ever refer to an object of Thread. This makes o==s work and o==t also work but s==t doesn't work, as it simply fails to compile.

Tags:

Java