Understanding == operator for Object Comparison in Java

Viewed 260

I understand that == operator checks for equal references(addresses) but I am not getting how the compiler is throwing below error when comparing Thread and String object.

java: incomparable types: java.lang.Thread and java.lang.String

Here is my code:

public static void main(String[] args) {
    Thread t = new Thread();
    Object o = new Object();
    String s = new String("");

    System.out.println(t == o);//no issues here

    System.out.println(t==s);// but this throws above error
  }

Why is it allowing comparison between Thread and Object but not Thread and String?

3 Answers

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.

Simply, this is happening because an Object can be anything. It is changeable and can be assigned to multiple things. As explained by @nits.kk, Since Thread extends Object and String extends Object. It makes it possible to use t == o and s == o since they are both considered as an Object. However, string is very different from thread even though they are both objects, they are not in the same category. Hence, they cannot be compared and it will throw a compile error as explained by @Progman.

Related