Java String.contentEquals
Compare a String with the text in a CharSequence such as a StringBuilder.
A simple example
String.contentEquals
- Start with "ab" and a buffer holding ab
- Do this Compare the characters
- Result Equal
class Main {
public static void main(String[] args) throws Exception {
System.out.println("ab".contentEquals(new StringBuilder("ab")));
}
}
true
Syntax
public boolean contentEquals(StringBuffer sb)
JDK 21 method signatures (2)
public boolean contentEquals(StringBuffer sb)
public boolean contentEquals(CharSequence cs)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCheck a ticket assembled by a scanner
A scanner builds a label incrementally in a buffer before checking it against a stored code. Compare the completed characters and ensure that a partial scan cannot be accepted as the whole ticket.
class Main {
public static void main(String[] args) throws Exception {
StringBuilder scan = new StringBuilder("AB").append(17);
System.out.println("AB17".contentEquals(scan));
}
}
true
The builder contains the same four characters as the expected code.
Detect a missing item on a printed receipt
A receipt check searches for an expected item among the printed entries. Handle the missing case explicitly so the next step cannot accidentally treat an unsuccessful lookup as a valid position.
class Main {
public static void main(String[] args) throws Exception {
var receipt = new StringBuffer("tea, rice");
System.out.println("tea, rice, oats".contentEquals(receipt));
}
}
false
The buffer ends before the final item.
Validate a locker ticket
The first reading comes from the ticket and the second from the lock. The reader compares both identifiers character for character. Do the two spellings match?
What to watch for
equals only accepts another String as an equal value. contentEquals can compare the contents of a mutable buffer.