Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking object reference equality using == (in Java) [duplicate]

Tags:

java

Why does...

    String a = new String("a");
    StringBuilder b = new StringBuilder("a");
    System.out.println(a==b);

... result in an incompatible types error when compiling given that...

    String a = new String("b");
    Object b = new StringBuilder("b");
    System.out.println(a==b);

... does not?

Why can I compare the object references of a String and an Object but not a StringBuilder and a String? Aren't they all just addresses to memory locations?

Thanks

like image 986
Kayl669 Avatar asked Apr 23 '15 09:04

Kayl669


People also ask

How to check the equality of two objects in Java?

We can use the equals () method in Java to check the equality of two objects. The equals () method is given to compare two objects of a class for their equality based on their reference or based on data. The equals () method is defined in java.lang.Object class and compare two objects based on their reference.

What is the use of equals in Java?

Java Object equals (Object obj) Method equals (Object obj) is the method of Object class. This method is used to compare the given objects. It is suggested to override equals (Object obj) method to get our own equality condition on Objects.

What is equals(Object OBJ) in Java?

Java Object equals(Object obj) Method. equals(Object obj) is the method of Object class. This method is used to compare the given objects. It is suggested to override equals(Object obj) method to get our own equality condition on Objects. obj - it is the reference object.

How to demonstrate object class equals() method in Java?

Examples to demonstrate Object class equals () method in Java, The t1 and t2 are two different objects of Test class, t3 is pointing to the reference of object t1. Hence, t1 and t2 have different references but t3 and t1 are having the same reference. The equals () method is called on these objects.


1 Answers

Acording to the Java Language Specification (15.21.3):

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

Which means, in order to "compare" two reference types, one should be able to be cast to the other. String "is" an object, but there is no "cast" between String and StringBuilder.

like image 178
morgano Avatar answered Nov 15 '22 10:11

morgano