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
?
In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables).
When using the comparison operator ( == ), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values (values are compared with == ), and are instances of the same class.
== operator is a type of Relational Operator in Java used to check for relations of equality. It returns a boolean result after the comparison and is extensively used in looping statements and conditional if-else statements.
The == operator compares whether two object references point to the same object. For example: System.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With