Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding == operator for Object Comparison in Java

Tags:

java

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?

like image 330
Rahul Gupta Avatar asked Jul 15 '20 19:07

Rahul Gupta


People also ask

Can you use == to compare objects in Java?

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).

Can == compare objects?

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.

What does the == operator do in Java?

== 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.

Can you use == with objects?

The == operator compares whether two object references point to the same object. For example: System.


Video Answer


2 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).

like image 60
Progman Avatar answered Oct 25 '22 01:10

Progman


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.

like image 26
nits.kk Avatar answered Oct 25 '22 01:10

nits.kk