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.
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
