contentEquals() String Example

contentEquals() String Example

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.

contentEquals() String
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.

Leave a Reply

Your email address will not be published. Required fields are marked *