repeat()
Returns the String repeated a given number of times, the Java 11 replacement for padding loops and hand-built separator lines.
public String repeat(int count)- Added in Java Java 11
Parameters
| Parameter | Type | Description |
|---|---|---|
$count | int | How many times to repeat. Must not be negative. |
Return value
StringA String made of this String repeated count times. Returns an empty String if count is 0 or this String is empty.
Errors
IllegalArgumentException if count is negative. A result too large for a String fails with OutOfMemoryError.
s.repeat(n) returns s concatenated n times. Before Java 11 this took a loop with a StringBuilder, or tricks with String.join and Collections.nCopies. Now it is one call, and it sizes the result once instead of growing a buffer.
"-".repeat(20) // "--------------------"
"ab".repeat(3) // "ababab"
"x".repeat(0) // ""Rules
- A count of 0, or an empty String, gives an empty String.
- A negative count throws
IllegalArgumentException. This bites padding code:" ".repeat(width - s.length())throws when the value is wider than the column. Wrap the count inMath.max(0, ...). - If the result would exceed the maximum String size, it fails with
OutOfMemoryErrorinstead of returning.
Where it helps in back-end code
Padding is the obvious use: zero-padding invoice or ticket numbers to a fixed width, indenting nested output, or aligning plain-text reports and CLI tables. For numbers, String.format("%08d", n) does the same job and also handles negative values; repeat works for any text, including ids that are not numbers.
It is also handy in tests. A request body limit, a column size or a header size limit needs input just over the boundary, and "a".repeat(1024 * 1024 + 1) builds it in one line. Remember that limits are often in bytes: "\u00e9".repeat(600) is 600 chars but 1200 bytes in UTF-8.
For masking secrets, repeat a mask char to the length you want to hide and append the visible tail, as shown in the substring lesson. Avoid revealing the exact length of a password; a fixed number of mask chars is safer.
The result is a new String; the original is unchanged.
Example
When to use it
- Zero-padding invoice or ticket numbers to a fixed width before printing them.
- Generating payloads exactly at and just over a body size limit in tests.
- Indenting nested output or drawing separator lines in a CLI or plain-text report.
Frequently asked questions
How do I repeat a String n times in Java?
Since Java 11, use s.repeat(n). On older versions, String.join("", Collections.nCopies(n, s)) or a StringBuilder loop does the same.
Why does repeat throw IllegalArgumentException?
The count is negative. This usually comes from padding code such as " ".repeat(width - s.length()) when s is longer than width; clamp the count with Math.max(0, ...).
More examples
A plain-text table
Each cell is padded to the column width with repeated spaces, and Math.max keeps a long cell from causing an IllegalArgumentException. stripTrailing removes the padding after the last column.
void main() {
List<String[]> rows = List.of(
new String[] {"GET", "/orders", "200"},
new String[] {"POST", "/orders", "201"},
new String[] {"DELETE", "/orders/7", "204"});
int w = 10;
for (String[] r : rows) {
StringBuilder line = new StringBuilder();
for (String cell : r) {
line.append(cell).append(" ".repeat(Math.max(0, w - cell.length())));
}
IO.println(line.toString().stripTrailing());
}
IO.println("=".repeat(w * 3));
}
// Output:
// GET /orders 200
// POST /orders 201
// DELETE /orders/7 204
// ==============================Testing a request size limit
repeat builds boundary-sized payloads in one line: exactly at the limit and one byte over. The accented text shows why a limit in bytes and a limit in chars give different answers.
boolean fits(String body, int maxBytes) {
return body.getBytes(StandardCharsets.UTF_8).length <= maxBytes;
}
void main() {
String small = "a".repeat(1024);
String big = "a".repeat(1024 * 1024 + 1);
IO.println(fits(small, 1024) + " " + fits(big, 1024 * 1024));
String accents = "\u00e9".repeat(600);
IO.println(accents.length() + " chars, " + accents.getBytes(StandardCharsets.UTF_8).length + " bytes");
IO.println(fits(accents, 1024));
}
// Output:
// true false
// 600 chars, 1200 bytes
// falseZero-padding identifiers
The guard leaves values that are already wide enough alone instead of throwing. String.format gives the same result for numbers; repeat also works for text ids.
String pad(String s, int width) {
return s.length() >= width ? s : "0".repeat(width - s.length()) + s;
}
void main() {
IO.println(pad("42", 8));
IO.println(pad("123456789", 8));
IO.println(String.format("%08d", 42));
}
// Output:
// 00000042
// 123456789
// 00000042
Discussion