-2
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?

Ashish Ani
  • 324
  • 1
  • 7
  • 2
    The main reason for this behaviour is due to this line in code of String class equals method: 1017 if (anObject instanceof String) { // hence if an Object passed in equals method must be an instanceOf String only. Otherwise it always returns false. – Ashish Ani Nov 30 '15 at 06:16

2 Answers2

3

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

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
-1

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`
Abdelhak
  • 8,299
  • 4
  • 22
  • 36