Repeat a String N Times in Java: repeat() and Alternatives

Repeat a string N times in Java with String.repeat(), StringBuilder.repeat(), String.join() with nCopies, Java 8 loops and StringUtils, with edge cases.

Diagram of "ab".repeat(3) copying the two characters three times into a new string of length 6, plus the results for a zero, empty, negative and too large count

The simplest way to repeat a string N times in Java is str.repeat(n), which returns a new string made of n copies of str joined together. The method belongs to String, so it needs no loop, no library and no regex.

We repeat strings to draw separator lines in console output, to indent nested items, to pad values to a fixed width and to build test data or SQL placeholders.

The following example repeats a string in the ways this article covers, with the result of each line in the comment.

String line = "-".repeat(5);                                  // "-----"
String word = "ab".repeat(3);                                  // "ababab"
String none = "ab".repeat(0);                                  // ""
String built = new StringBuilder("|").repeat("ab", 2).toString();   // "|abab"
String joined = String.join(",", Collections.nCopies(3, "?"));      // "?,?,?"
String oldWay = new String(new char[3]).replace("\0", "ab");        // "ababab"

Notice that only String.join() with Collections.nCopies() puts a separator between the copies. We start with the rules of repeat(), including the two inputs that throw, and move on to characters, StringBuilder, separators, Java 8 code and the two common libraries.

1. The String.repeat() Method

The method repeat(int count) returns a string whose value is the original string concatenated count times. The original string stays unchanged, because strings are immutable, so we always use the returned value.

Diagram of "ab".repeat(3) copying the two characters three times into a new string of length 6, plus the results for a zero, empty, negative and too large count
The call “ab”.repeat(3) returns a new string of length 6, a count of 0 returns an empty string, and a negative count throws an exception
String stars = "*".repeat(8);              // "********"
String pair = "ab".repeat(1);               // "ab"
String empty = "".repeat(100);              // ""
int length = "abc".repeat(4).length();      // 12

The result length is always the source length times the count. Two inputs do not produce a string at all.

  • A negative count throws an IllegalArgumentException with the message count is negative.
  • A count so large that the result would exceed the maximum string length throws an OutOfMemoryError before any memory is allocated.
String negative = "ab".repeat(-1);                      // IllegalArgumentException: count is negative: -1
String tooLong = "abcde".repeat(Integer.MAX_VALUE);     // OutOfMemoryError: Required length exceeds implementation limit

When the count comes from user input or a calculation, we clamp it with Math.max(0, n) before calling repeat(). A width calculation such as maxWidth – value.length() turns negative as soon as one value is longer than the column, and that is the most common source of the exception.

String value = "Inception";
int padding = 6 - value.length();                        // -3
String safePad = " ".repeat(Math.max(0, padding));       // ""

The method was added in Java 11 (JDK-8197594), as listed in our Java new features overview, and it works the same way in Java 25.

2. Repeating a Single Character

Java has no char.repeat(), so we turn the character into a one-character string first. For a character outside the Basic Multilingual Plane, such as an emoji, we work with the code point, because one such character takes two char values.

char dot = '.';
String dots = String.valueOf(dot).repeat(4);                    // "...."
int smileLength = Character.toString(0x1F600).repeat(2).length();   // 4
String bar = new StringBuilder().repeat('=', 6).toString();     // "======"

Repeating a character is how we build left padding with spaces or zeros by hand, e.g. “0”.repeat(width – digits.length()) + digits, although String.format(“%05d”, n) is shorter for numbers.

3. Appending Copies With StringBuilder.repeat()

Java 21 added two repeat() methods to StringBuilder, one that takes a CharSequence and one that takes a code point. They append the copies to the builder in place and return the same builder, so we can chain them without creating a temporary string for each part.

StringBuilder row = new StringBuilder();
row.append('+').repeat("-", 8).append('+').repeat("-", 5).append('+');
String border = row.toString();                    // "+--------+-----+"

We use the StringBuilder version inside loops that build a larger text, such as a table or a report, where “-“.repeat(8) would create one extra string per call.

4. Repeating With a Separator

The method repeat() glues the copies together with nothing between them. When we need a delimiter, we create a list of n equal elements with Collections.nCopies() and join it with String.join(). The list from nCopies() stores the element only once, so it costs almost no memory.

Say a library app loads the books for a list of IDs with one SQL query. A PreparedStatement needs one ? placeholder per ID in the IN clause, so the number of placeholders changes with every request.

List<Long> bookIds = List.of(7L, 12L, 31L);
String marks = String.join(", ", Collections.nCopies(bookIds.size(), "?"));    // "?, ?, ?"
String sql = "SELECT * FROM book WHERE id IN (" + marks + ")";            // "SELECT * FROM book WHERE id IN (?, ?, ?)"

The values themselves are bound with setLong() afterwards, so the query stays safe from SQL injection. A stream with Collectors.joining() produces the same text and also lets us add a prefix and a suffix.

String inClause = Stream.generate(() -> "?").limit(3).collect(Collectors.joining(", ", "(", ")"));   // "(?, ?, ?)"

5. Repeating a String in Java 8

Code that still runs on Java 8 cannot call repeat(). The cleanest replacement there is a StringBuilder sized for the result, and we wrap it in a small helper method.

static String repeat(String text, int count) {
    if (count < 0) {
        throw new IllegalArgumentException("count is negative: " + count);
    }
    StringBuilder sb = new StringBuilder(text.length() * count);
    for (int i = 0; i < count; i++) {
        sb.append(text);
    }
    return sb.toString();
}
String viaLoop = repeat("ab", 3);                                   // "ababab"
String viaArray = new String(new char[3]).replace("\0", "ab");      // "ababab"
String viaCopies = String.join("", Collections.nCopies(3, "ab"));    // "ababab"

The char[] version creates an array of three \0 characters, the default value of a char, and replaces each one with the string. The method replace(CharSequence, CharSequence) does a literal replacement, not a regex replacement, so the trick works for any text. It breaks only when the source string itself contains \0.

We avoid a loop with result += text, because every pass copies the whole result built so far into a new string. For large counts the work grows with the square of the count, as explained in String concatenation performance.

6. Apache Commons Lang and Guava

Many projects already have Apache Commons Lang or Guava on the classpath. Both have a repeat() helper, and Commons Lang also has a version with a separator and one that treats null input safely.

String commons = StringUtils.repeat("ab", 3);              // "ababab"
String withSep = StringUtils.repeat("ab", "-", 3);        // "ab-ab-ab"
String nullSafe = StringUtils.repeat(null, 3);            // null
String guava = Strings.repeat("ab", 3);                   // "ababab"

On Java 11 and later, we use String.repeat() for the plain case and keep the libraries for the extras, such as the separator version of StringUtils.repeat().

7. Printing a Text Report With Repeated Characters

A command-line tool for a video library prints the movies of each genre as an indented tree, under a title with a line of the same width. Both the indentation and the line come from repeat(), with the depth or the title length as the count.

static String indent(int depth, String label) {
    return "  ".repeat(depth) + "- " + label;
}
String title = "Movies by genre";
String underline = "=".repeat(title.length());          // "==============="
String genre = indent(0, "Drama");                       // "- Drama"
String movie = indent(1, "Inception");                   // "  - Inception"

Printed one after another, these lines give the following output.

Movies by genre
===============
- Drama
  - Inception

For aligned columns with different widths, the format specifiers of String.format() are a better fit than repeated spaces, as shown in aligning text in columns.

8. Choosing a Way to Repeat a String N Times in Java

All the ways return the same text for the plain case. They differ in the Java version they need and in whether they add a separator.

CodeSinceSeparatorNotes
str.repeat(n)Java 11NoShortest; throws for a negative n
sb.repeat(str, n)Java 21NoAppends to an existing StringBuilder
String.join(sep, Collections.nCopies(n, str))Java 8YesGood for placeholders and lists
Stream.generate(…).limit(n).collect(joining(…))Java 8Yes, plus prefix and suffixLonger, but flexible
StringBuilder loopJava 1.5NoUse on Java 8 and older
new String(new char[n]).replace(“\0”, str)Java 1.5NoA trick; hard to read
StringUtils.repeat(str, sep, n)Commons LangOptionalnull input returns null
Strings.repeat(str, n)GuavaNoThrows for null input

9. Repeat String FAQs

Java versions, zero counts, speed and separators are what developers search for after their first repeat() call.

9.1. Which Java version added String.repeat()?

Java 11. The StringBuilder.repeat() methods came later, in Java 21. On Java 8 we use a StringBuilder loop or String.join() with Collections.nCopies(), as shown in section 5.

9.2. What does repeat(0) return?

An empty string. The same happens when the source string is empty, whatever the count is. Only a negative count throws an exception.

9.3. Is repeat() faster than a loop?

Yes, compared with a loop that uses +=. The method repeat() computes the final length first, allocates the array once and copies the source into it. A StringBuilder loop with the right capacity does similar work, but takes more code.

9.4. How do I repeat a string with a space between the copies?

We call String.join(” “, Collections.nCopies(n, str)). The expression (str + ” “).repeat(n).strip() gives the same result for most text, but it also removes spaces that belong to the string itself.

10. Conclusion

On Java 11 and later, str.repeat(n) is the way to repeat a string N times. It returns an empty string for a count of zero and throws an IllegalArgumentException for a negative count, so we clamp counts that come from calculations.

For copies with a separator, String.join() with Collections.nCopies() is the standard tool, and since Java 21 a StringBuilder can repeat text in place. The StringBuilder loop remains the clean choice for Java 8 code.

11. References

Happy Learning !!

Source Code on Github

Leave a Comment

  1. Are you saying that regex can be used for jdk <=14, but it is recommended only if jdk <= 10, since 'repeat's is avail in jdk 11?

    How you wrote this implies jdk 11 will not work for regex.
    "If you are working on JDK <= 10, then you may consider using regex to repeat a string N times."

  2. What is the solution, when the n times is of data type Long. The above mentioned methods are not supporting long data type. Only int data types are supported. Can you help me with this.

Comments are closed.

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.