Java .equals between String and StringBuilder

Because they both are Different objects.

String object!= StringBuilder object.

But,Your doubt is

name1.equals(s)  returning true

Because in String class equals method ovverided in such a way.

And to get the desired output convert your StringBuilder to String.

System.out.println(s.equals(sb.toString())); //return true.

If you see the Source code of String#equals()

1012    public boolean  equals(Object anObject) {
1013        if (this == anObject) {
1014            return true;
1015        }
1016        if (anObject instanceof String) {             //key line 
1017            String anotherString = (String)anObject;
1018            int n = count;
1019            if (n == anotherString.count) {
1020                char v1[] = value;
1021                char v2[] = anotherString.value;
1022                int i = offset;
1023                int j = anotherString.offset;
1024                while (n-- != 0) {
1025                    if (v1[i++] != v2[j++])
1026                        return false;
1027                }
1028                return true;
1029            }
1030        }
1031        return false;
1032    }

The line if (anObject instanceof String) { always returns false incase if you pass StringBuilder.

Leave a Comment