String.repeat()
Repeats a string the given number of times.
Available since: Java 11
Syntax
public String repeat(int count)Parameters
| Parameter | Type | Description |
|---|---|---|
| count | int | How many times to repeat. 0 gives an empty string, a negative number throws an exception. |
Return value
StringA new string.
Examples
A line of characters and a simple staircase:
void main() {
IO.println("-".repeat(10));
for (int i = 1; i <= 3; i++) {
IO.println("*".repeat(i));
}
}Output:
----------
*
**
***Notes
Before Java 11 this needed a loop with StringBuilder. A negative count throws IllegalArgumentException.
See also
- String.join() — Joins strings with a separator.
- StringBuilder — A mutable string: useful when text is built piece by piece, especially in a loop.
Related recipes
In the tutorial
- String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.