String s = new String("Abc");
StringBuilder s1 = new StringBuilder("Abc");
System.out.println(s.equals(s1));
Output: false
Why ?? Can anyone explain me about this?
String s = new String("Abc");
StringBuilder s1 = new StringBuilder("Abc");
System.out.println(s.equals(s1));
Output: false
Why ?? Can anyone explain me about this?
A String
is not a StringBuilder
, so why do you expect them to be equal?
s.equals(s1.toString())
will return true, since that would be a comparison of two String
s.
String
's equals
is implemented as :
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
...
}
return false;
}
When anObject
is not an instance of String
(and only String
can be an instance of String
, since the String
class is final), equals
returns false.
Java provides the StringBuffer and String classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be modified.
In this case when you have:
String s = new String("Abc");
StringBuilder s1 = new StringBuilder("Abc");
System.out.println(s.equals(s1));
Gives false
because in StringBuffer class equals
method is not overriden as in String class.
Therefore you first need to convert that to a String and then use equals method like this:
s.equals(s1.toString()) gives `true`