In Java, repeat(count) returns a new String made of the original text written count times in a row: "ab".repeat(3) is "ababab". A count of 0 gives the empty string.
It replaces the old loop-and-append pattern for things like separator lines, indentation, padding, and simple text charts, in one readable call.
repeat() is an instance method of java.lang.String, added in Java 11. Call it on a string, as in text.repeat(...); calling it on a null reference throws NullPointerException. Strings are immutable, so it never changes the original: it returns a new String (or the same one when nothing changes). Keep the result. Requires Java 11 or newer.
Repeating an empty string, or repeating once, simply gives back equal text. The result length is length() * count, so large counts can need a lot of memory.
Library declarations
java
public String repeat(int count);
Parameters
Parameter
Description
count
How many times to repeat; must be 0 or more.
Return Value
Return Value
Description
String
The text repeated count times, or "" for 0.
Java Examples
Example 1 — Repeat Text, Separators, and Nothing
Three counts: a few copies, a separator line, and zero.
java
public class RepeatBasic {
public static void main(String[] args) {
System.out.println("ab".repeat(3));
System.out.println("-".repeat(10));
System.out.println("[" + "x".repeat(0) + "]");
}
}
Output
ababab
----------
[]
How It Works
Copies side by side."ab".repeat(3) writes the two letters three times without any separator.
Instant separator lines. A one-char string repeated 10 times draws a line of dashes.
Zero copies. A count of 0 is legal and returns the empty string, shown as [].
Example 2 — Draw a Simple Bar Chart
Use each number as the repeat count of a bar.
java
public class RepeatBarChart {
public static void main(String[] args) {
String[] days = {"Mon", "Tue", "Wed"};
int[] sales = {3, 7, 5};
for (int i = 0; i < days.length; i++) {
System.out.println(days[i] + " " + "#".repeat(sales[i]) + " " + sales[i]);
}
}
}
Output
Mon ### 3
Tue ####### 7
Wed ##### 5
How It Works
Parallel arrays.days[i] and sales[i] describe the same day.
Count becomes length."#".repeat(sales[i]) produces a bar whose length equals the sales figure.
Readable at a glance. Tuesday's bar of 7 hashes is visibly the longest.
Example 3 — Right-Align Numbers and Reject a Negative Count
Pad each number with spaces to a width of six, then try a negative count.
java
public class RepeatAlign {
public static void main(String[] args) {
int[] numbers = {7, 42, 1234};
for (int n : numbers) {
String text = String.valueOf(n);
System.out.println(" ".repeat(6 - text.length()) + text);
}
try {
"a".repeat(-1);
} catch (IllegalArgumentException e) {
System.out.println("negative count: " + e.getClass().getSimpleName());
}
}
}