Discover Java 21’s New repeat() Method for StringBuilder and StringBuffer

Java 21 introduces repeat() overloads for StringBuilder and StringBuffer, allowing you to duplicate characters or CharSequence efficiently; the article demonstrates usage with sample code, explains the Unicode codePoint variant, and invites readers to explore creative applications of this new API.

Programmer DD
Programmer DD
Programmer DD
Discover Java 21’s New repeat() Method for StringBuilder and StringBuffer

Java 21 adds a repeat method to StringBuilder and StringBuffer.

@Override
public StringBuilder repeat(int codePoint, int count) {
    super.repeat(codePoint, count);
    return this;
}

@Override
public StringBuilder repeat(CharSequence cs, int count) {
    super.repeat(cs, count);
    return this;
}

Try the method with a simple example:

var sb = new StringBuilder().repeat("*", 10);
System.out.println(sb);

The program prints:

**********
The overload whose first parameter is codePoint repeats a Unicode code point, so it works with Unicode characters.

This API can be handy for quickly building text separators or other repeated patterns; feel free to experiment with other uses.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaCode ExampleJava 21stringbuilderstringbufferrepeat method
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.