StringBuilder .equals Java

The default implementation of .equals for the Object class is as you mentioned.

Other classes can override this behavior. StringBuilder is not one of them.

String is one of them, which overrides it to ensure that the String representations of both objects result in the same sequence of characters. String API

Refer to the documentation for the specific object in question.


Yes, StringBuilder does not override Object's .equals() function, which means the two object references are not the same and the result is false.

For StringBuilder, you could use s1.toString().equals(s2.toString())

For your edit, you're calling the == operator on two different String objects. The == operator will return false because the objects are different. To compare Strings, you need to use String.equals() or String.equalsIgnoreCase()

It's the same problem you were having earlier


The StringBuilder class does not provide an overriden equals() method. As such, when that method is called on an instance of StringBuilder, the Object class implementation of the method is executed, since StringBuilder extends Object.

The source code for that is

public boolean equals(Object obj) {
    return (this == obj);
}

Which simply compares reference equality.

Tags:

Java