Library contents

Java String.contentEquals

Compare a String with the text in a CharSequence such as a StringBuilder.

A simple example

String.contentEquals

  1. Start with "ab" and a buffer holding ab
  2. Do this Compare the characters
  3. Result Equal
Both sequences hold a followed by b, even though the container types differ.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("ab".contentEquals(new StringBuilder("ab")));
    }
}
Output
true

Syntax

Java 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.java

Check 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.

Resulttrue
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        StringBuilder scan = new StringBuilder("AB").append(17);
        System.out.println("AB17".contentEquals(scan));
    }
}
Output
true

The builder contains the same four characters as the expected code.

Advertisements

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.

Resultfalse
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        var receipt = new StringBuffer("tea, rice");
        System.out.println("tea, rice, oats".contentEquals(receipt));
    }
}
Output
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?

Given'H07' · 'H07'
Worked resultMatch

What to watch for

equals only accepts another String as an equal value. contentEquals can compare the contents of a mutable buffer.

Documentation for String.contentEquals