is String and StringBuffer are incompatible types?
when we performs equals test on String and StringBuffer at line no 3 why they are not showing result sb equals s1.
euals does not mean meaningfully equivalent
the equals method of the StringBuffer class is not implemented so there is no way to campary a String object with a StringBuffer object, to compare those values you have to do yourString.equals(yourStringBuffer.toString());
also try testing two StringBuffers that holds the same string using the equals() method you will see that it will return false.
StringBuffer sb1 = new StringBuffer("123");
StringBuffer sb2 = new StringBuffer("123");
System.out.println("sb1.equals(sb2) --> " + sb1.equals(sb2));
the result will be ... false
Omar Al Kababji - Electrical & Computer Engineer
[SCJP - 90% - Story] [SCWCD - 94% - Story] [SCBCD - 80% - Story] | My Blog
is String and StringBuffer are incompatible types?
I think the compiler says that java.lang.StringBuffer and java.lang.String are incomparable (not incompatible) types because they are not part of the same class hierarchy, and for this reason there is no way for s and sb to reference the same object.
At line 3, it will give compiler error as sb and s are of different types(StringBuffer and String respectively).
Operands of == operator should be type compatible.
And StringBuffer class doesnt override the equals() method. So when you use equals() method on StringBuffer object, it checks if both are referring to the same object or not. (not meaningful equivalence).
omar al kababji wrote:the equals method of the StringBuffer class is not implemented so there is no way to campary a String object with a StringBuffer object, to compare those values you have to do yourString.equals(yourStringBuffer.toString());
also try testing two StringBuffers that holds the same string using the equals() method you will see that it will return false.
StringBuffer sb1 = new StringBuffer("123");
StringBuffer sb2 = new StringBuffer("123");
System.out.println("sb1.equals(sb2) --> " + sb1.equals(sb2));
the result will be ... false
Why is it so that when using StringBuffer equals() gives false even if they both have same data("123")..
Apoorv Srivastava wrote:
Why is it so that when using StringBuffer equals() gives false even if they both have same data("123")..
Because StringBuffer doesn't override the equals() method defined in Object, which in turn uses == in its implementation. Therefore, when you use equals() with StringBuffer references what you are checking is if the references actually refer to the same object (not if the objects they refer to are meaningfully equivalent.)
All code in my posts, unless a source is explicitly mentioned, is my own.
StringBuffer doesn't override the equals() method defined in Object, but actually inherits it. Therefore, when you use equals() on StringBuffer, it actually checks if the references actually refer to the same object