We know earlier equals() method is used to compare two strings whether they have same sequence of characters or not. But this method cannot compare String with StringBuffer. Even if they have same characters, the equals() returns false. In this case use contentEquals() String.
contentEquals() String method is useful to compare String with StringBuffer or StringBuilder. The method returns a boolean value if they contain the same sequence (order) of characters.
Following is the method signature of contentEquals() String.
- public boolean contentEquals(StringBuffer sb): Compares String with StringBuffer. Returns true if both objects contain same sequence of characters, else false. Introduced with JDK 1.4.
Following example illustrates the usage of the above method.
public class StringMethodDemo
public static void main(String args)
String str1 = "ABCD";
String str2 = "ABCD";
StringBuffer buffer1 = new StringBuffer("ABCD");
StringBuffer buffer2 = new StringBuffer("ABCD");
StringBuilder builder1 = new StringBuilder("ABCD");
System.out.println("Two StringBuffer's of same characters with equals(): " + buffer1.equals(buffer2)); // false
System.out.println("String with StringBuffer of same characters with equals(): " + str1.equals(buffer1)); // false
System.out.println("\nString with StringBuffer of same characters with contentEquals(): " + str1.contentEquals(buffer1)); // true
System.out.println("String with StringBuilder of same characters with contentEquals(): " + str1.contentEquals(builder1)); // true
Output screen on contentEquals() String Example Example
1. Observe, buffer1.equals(buffer2) returned false eventhough buffer1 and buffer2 comes with same characters.
2. str1.equals(buffer1) returned false eventhough str1 and buffer1 comes with same characters.
3. str1.contentEquals(buffer1) and str1.contentEquals(builder1) returned true as contentEquals() is meant to compare String with StringBuffer and StringBuilder.