CKTIS / Java
Comparing text with String.contentEquals
Compare a String with a CharSequence or StringBuffer without converting the argument to String.
Version: Java SE 21
Syntax
// Method declaration headers in java.lang.String
public boolean contentEquals(CharSequence cs)
public boolean contentEquals(StringBuffer sb)String.contentEquals(CharSequence) checks for the same UTF-16 code units (char values) in the same order. The comparison is case-sensitive, does not normalize Unicode, and works with a StringBuilder without converting it to String. In contrast, String.equals(Object) only matches another String with identical content. contentEquals(StringBuffer) locks the buffer, and the CharSequence overload does so too if the argument is actually a StringBuffer. Both contentEquals overloads throw NullPointerException for null.
Examples
public class StringContentDemo {
public static void main(String[] args) {
String text = "abcd\u00E9";
CharSequence sequence = new StringBuilder(text);
System.out.println("contentEquals: " + text.contentEquals(sequence));
System.out.println("equals: " + text.equals(sequence));
StringBuffer buffer = new StringBuffer(text);
System.out.println("contentEquals(StringBuffer): " + text.contentEquals(buffer));
buffer.append('!');
System.out.println("contentEquals(StringBuffer) after append: " + text.contentEquals(buffer));
}
}
Result
contentEquals: true equals: false contentEquals(StringBuffer): true contentEquals(StringBuffer) after append: false
The `StringBuilder` has matching content but is not a `String`, so `contentEquals` returns `true` and `equals` returns `false`. The `StringBuffer` overload returns `true` before `!` is appended and `false` afterward.
Related lessons
- Java · Lesson 51 · Advanced · Version: 2