The contentEquals() method compares a String with any CharSequence—such as another String, a StringBuilder, or a StringBuffer—by character content rather than object identity. It returns true or false.
01
Content Compare
Characters, not references.
02
CharSequence
StringBuilder works.
03
Returns boolean
true or false.
04
Case Sensitive
A ≠ a by default.
05
vs equals()
Mutable types too.
06
Validation
Built text vs target.
Fundamentals
Definition and Usage
In Java, contentEquals(CharSequence cs) is defined on java.lang.String. It walks both sequences character by character and returns true only when every character and the total length match.
This method shines when you accumulate text in a StringBuilder or StringBuffer and need to verify it matches an expected String. You can compare directly without calling builder.toString() first.
💡
Beginner Tip
equals() on a String only compares content when the other object is also a String. Use contentEquals() when the other side is a StringBuilder or StringBuffer.
Foundation
📝 Syntax
The contentEquals() method is declared in the String class:
java
public boolean contentEquals(CharSequence cs)
Parameters
cs — the character sequence to compare against. Must not be null.
Return Value
Returns true if both sequences contain the same characters in the same order and have the same length; otherwise false.
Exceptions
Throws NullPointerException if cs is null.
Cheat Sheet
⚡ Quick Reference
Expression
Result
"Hello".contentEquals("Hello")
true
"Hello".contentEquals(new StringBuilder("Hello"))
true
"Hello".contentEquals("hello")
false (case-sensitive)
"Hi".contentEquals("Hi there")
false (different length)
str.equals(builder)
false (different types)
StringBuilder
str.contentEquals(builder)
Compare built text
StringBuffer
str.contentEquals(buffer)
Thread-safe builder
Ignore case
s.equalsIgnoreCase(other)
When both are Strings
Null guard
cs != null && str.contentEquals(cs)
Avoid NPE
Hands-On
Examples Gallery
These programs run in Java 8+. They show matching content with StringBuilder, failed comparisons, case rules, StringBuffer, and how contentEquals() differs from equals().
📚 Getting Started
Compare a String with a StringBuilder that holds the same text.
Example 1 — String and StringBuilder Match
When both sequences contain "Hello, World!", contentEquals() returns true.
java
public class ContentEqualsExample {
public static void main(String[] args) {
String str = "Hello, World!";
StringBuilder builder = new StringBuilder("Hello, World!");
boolean result = str.contentEquals(builder);
if (result) {
System.out.println("The contents are equal.");
} else {
System.out.println("The contents are not equal.");
}
}
}
📤 Output:
The contents are equal.
How It Works
Java compares character by character across the String and the StringBuilder. Because every character and the length match, the method returns true.
Example 2 — Different Content
When lengths or characters differ, contentEquals() returns false without throwing an exception.
java
public class NotEqualDemo {
public static void main(String[] args) {
String expected = "Java Programming";
StringBuilder actual = new StringBuilder("Java Program");
System.out.println("Match? " + expected.contentEquals(actual));
}
}
📤 Output:
Match? false
How It Works
actual is missing ming at the end, so the sequences differ. The comparison stops and returns false.
📈 Practical Patterns
Case rules, mutable buffers, and choosing the right comparison method.
Example 3 — Case-Sensitive Comparison
Letter case matters. Java and java are not equal content.
java
public class CaseSensitiveContent {
public static void main(String[] args) {
String label = "Learn Java Today";
System.out.println("Equals 'Java'? " + label.contentEquals("Java"));
System.out.println("Equals 'java'? " + label.contentEquals("java"));
}
}
📤 Output:
Equals 'Java'? false
Equals 'java'? false
How It Works
contentEquals() requires an exact full-sequence match—not a substring. Neither "Java" nor "java" equals the entire string "Learn Java Today", so both results are false.
Example 4 — Comparing with StringBuffer
StringBuffer also implements CharSequence, so it works the same way as StringBuilder.
java
public class BufferCompare {
public static void main(String[] args) {
String target = "codetofun";
StringBuffer buffer = new StringBuffer();
buffer.append("code").append("to").append("fun");
System.out.println("contentEquals: " + target.contentEquals(buffer));
}
}
📤 Output:
contentEquals: true
How It Works
The buffer was built in pieces, but the final character sequence matches target. contentEquals() compares the assembled content, not how it was constructed.
Example 5 — contentEquals() vs equals()
equals() returns false for a StringBuilder because the types differ, even when the text matches.
java
public class ContentEqualsVsEquals {
public static void main(String[] args) {
String str = "Hello";
StringBuilder builder = new StringBuilder("Hello");
System.out.println("equals(): " + str.equals(builder));
System.out.println("contentEquals(): " + str.contentEquals(builder));
System.out.println("equals(toString): " + str.equals(builder.toString()));
}
}
equals(Object) on String only compares content when the argument is another String. contentEquals() bridges that gap for any CharSequence.
Applications
🚀 Common Use Cases
StringBuilder validation — confirm assembled output matches an expected constant or template.
Parsing pipelines — compare a token read into a buffer against a known keyword.
Test assertions — verify builder-based code produces the correct final text.
Legacy StringBuffer code — compare thread-safe buffers without extra conversions.
Protocol or config checks — match a built header or message against a required value.
🧠 How contentEquals() Works
1
You pass a CharSequence
The host String and the argument can be different concrete types.
Input
2
Null is rejected
A null argument throws NullPointerException immediately.
Validate
3
Length then characters
If lengths differ, return false. Otherwise compare each character in order.
Compare
=
✅
boolean answer
true when every character matches; false otherwise.
Important
📝 Notes
contentEquals() compares full sequence content, not object references.
It is case-sensitive. Normalize case or use equalsIgnoreCase() when both sides are String objects.
It requires an exact match of the entire sequence—unlike contains(), which searches for a substring.
The parameter type is CharSequence, so String, StringBuilder, and StringBuffer all work.
Passing null throws NullPointerException—unlike some utility methods that accept null safely.
Performance
⚡ Optimization
contentEquals() is optimized for direct character-sequence comparison and avoids creating a temporary String from a StringBuilder when you would otherwise call builder.toString() only for comparison. For repeated checks in a hot loop, cache the boolean result. When both operands are already String instances, equals() is equally appropriate and idiomatic.
Wrap Up
Conclusion
The contentEquals() method is the right tool when you need to compare a String with mutable character sequences or any other CharSequence by content. It keeps comparisons readable and avoids unnecessary toString() calls.
Remember that it is case-sensitive, compares the full sequence (not a substring), and differs from equals() when the other object is not a String. With those rules in mind, you can compare built text confidently in real programs.
Use contentEquals() when comparing a String to a StringBuilder or StringBuffer
Guard against null CharSequence arguments before calling
Use equals() when both operands are already String objects
Normalize case when user input may vary in capitalization
Prefer contentEquals() over equals(builder.toString()) when avoiding extra allocation matters
❌ Don’t
Assume contentEquals() ignores case (it does not)
Use it to find a substring inside a longer string (use contains() instead)
Pass null as the CharSequence argument
Expect equals() to work with StringBuilder the same way
Confuse reference equality (==) with content equality
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about contentEquals()
Use these points whenever you compare a String with other character sequences.
5
Core concepts
🔄01
Content Compare
Characters, not references.
Purpose
✅02
CharSequence
Builder and buffer.
Types
🔑03
Case Sensitive
Exact character match.
Edge case
📈04
vs equals()
Mutable types matter.
Compare
🔢05
Full Sequence
Not substring search.
Scope
❓ Frequently Asked Questions
contentEquals(CharSequence cs) compares the character sequence of the calling String with another CharSequence. It returns true when both sequences have the same length and the same characters in the same order.
equals(Object) on String compares content only when the other object is also a String. contentEquals(CharSequence) lets you compare a String directly with StringBuilder, StringBuffer, or any CharSequence without converting the mutable builder to a String first.
Yes. "Java".contentEquals("java") returns false because uppercase and lowercase letters are different. For case-insensitive checks, normalize both sides with toLowerCase() or use equalsIgnoreCase() when both operands are Strings.
Yes. That is the most common use case. str.contentEquals(builder) reads the builder's characters and compares them to the String's content without calling builder.toString().
The method throws NullPointerException because null is not a valid CharSequence argument. Validate or guard against null before calling.
Use it when you built text in a StringBuilder or StringBuffer and want to compare that result to a String literal or variable by content, especially in validation, parsing, or test assertions.