Difference between equals() and contentEquals() of String class

source code of String.equals

public boolean equals(Object anObject) {
	if (this == anObject) {
		return true;
	}
	if (anObject instanceof String) {
		String anotherString = (String)anObject;
		int n = count;
		if (n == anotherString.count) {
		char v1[] = value;
		char v2[] = anotherString.value;
		int i = offset;
		int j = anotherString.offset;
		while (n-- != 0) {
			if (v1[i++] != v2[j++])
			return false;
		}
		return true;
		}
	}
	return false;
}

source code of String.contentEquals

    public boolean contentEquals(CharSequence cs) {
        if (count != cs.length())
            return false;
        // Argument is a StringBuffer, StringBuilder
        if (cs instanceof AbstractStringBuilder) {
            char v1[] = value;
            char v2[] = ((AbstractStringBuilder)cs).getValue();
            int i = offset;
            int j = 0;
            int n = count;
            while (n-- != 0) {
                if (v1[i++] != v2[j++])
                    return false;
            }
        }
        // Argument is a String
        if (cs.equals(this))
            return true;
        // Argument is a generic CharSequence
        char v1[] = value;
        int i = offset;
        int j = 0;
        int n = count;
        while (n-- != 0) {
            if (v1[i++] != cs.charAt(j++))
                return false;
        }
        return true;
    }

 

The big difference is that equals() will only work with another String, while contentEquals() would work on any CharacterSequence (like StringBuilder).
http://www.coderanch.com

Here is an example

 
public class Test
{
    public static void main(String[] args)
    {
        String str1 = "Hello";
        String str2 = new String("Hello");
        StringBuilder str3 = new StringBuilder(str1);
 
        System.out.println("str1.equals(str2): " + (str1.equals(str2)));
        System.out.println("str1.contentEquals(str2): " + (str1.contentEquals(str2)));
        System.out.println("str1.equals(str3): " + (str1.equals(str3)));
        System.out.println("str1.contentEquals(str3): " + (str1.contentEquals(str3)));
    }
}