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