Java Reference ยท java.lang
Java String.repeat() method
Reference for Java String.repeat(int) from Java 11: repeat a string any number of times for separators, padding and indentation, plus its limits.
repeat() returns a new string made of the original string concatenated with itself the given number of times. It was added in Java 11 and replaces the loop or new String(new char[n]).replace('\0', c) tricks that were used before.
It is handy for dividers, indentation, padding and drawing simple text charts.
String line = "=".repeat(20); // "====================" String zero = "ab".repeat(0); // ""
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public String repeat(int count) // since 11
| Name | Description |
|---|---|
count |
How many copies to concatenate. Must not be negative. |
Returns: the repeated string. repeat(0) and repeating an empty string both return "". repeat(1) returns the original string itself.
Throws: IllegalArgumentException if count is negative. OutOfMemoryError if the result would be longer than the maximum string size (about 2 billion characters, and in practice limited by your heap).
Usage notes
- Cost is linear in the result length. The implementation allocates the final array once and fills it, so it is much faster than
+=in a loop. - It works on strings, not characters. For a single
charuseString.valueOf(c).repeat(n), orStringBuilder.repeat(int codePoint, int count)in Java 21 and later. - Computing a count carefully. Subtracting lengths can go negative; wrap it with
Math.max(0, ...)as in the padding example. - Not a formatter. For aligned columns,
%-10sand%10sinString.format()is usually clearer than repeating spaces by hand. - Overflow is checked. Huge
counttimes a long string reports an error rather than silently wrapping. - Java 8 and 10. The method does not exist there; use a
StringBuilderloop orString.join("", Collections.nCopies(n, s)).