Back to Blog
Java

Java String Repeat: Using String.repeat() and Alternatives

java string repeat: Learn how to repeat a string in Java using String.repeat(int) from Java 11, plus efficient alternatives for older Java versions.

JavaStringJava 11StringBuilderPerformance
Illustration of Java string repeat concept with a repeated character sequence.

java string repeat requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.

In Java, repeating a string is a common operation for padding, formatting, or generating test data. Since Java 11, the String class includes a repeat(int) method that does this directly. For older Java versions, you need a loop or a utility method. This article covers the built-in method, its behavior, and practical alternatives when you cannot rely on Java 11+.

Using String.repeat(int) in Java 11 and Later

The String.repeat(int count) method returns a new string that is the concatenation of the original string repeated count times. It is an instance method, so you call it on the string you want to repeat.

String word = "ab"; String repeated = word.repeat(3); System.out.println(repeated); // "ababab"

The method is simple and avoids manual loops. It is available on every String object and works with any character sequence, including empty strings and strings with Unicode characters.

How String.repeat(int) Behaves

The method accepts a single integer parameter. The behavior depends on the value of that parameter:

  • If count is 0, the result is an empty string.
  • If count is 1, the result is the original string.
  • If count is greater than 1, the string is repeated that many times.
  • If count is negative, the method throws IllegalArgumentException.
String s = "x"; System.out.println(s.repeat(0)); // "" System.out.println(s.repeat(1)); // "x" System.out.println(s.repeat(2)); // "xx"

Because repeat is an instance method, calling it on a null reference throws NullPointerException. There is no overload that accepts a CharSequence or a StringBuilder; the input must be a String.

The method returns a new string. It does not modify the original string, which is consistent with Java's immutable String design.

Repeating a String in Java 8 and Earlier

If your project runs on Java 8 or earlier, String.repeat is not available. You have several manual approaches. The most straightforward is a StringBuilder loop:

public static String repeat(String s, int count) { if (count < 0) { throw new IllegalArgumentException("count must be non-negative"); } StringBuilder sb = new StringBuilder(s.length() * count); for (int i = 0; i < count; i++) { sb.append(s); } return sb.toString(); }

Pre-sizing the StringBuilder with s.length() * count avoids reallocations during the loop. For a single-character string, you can use a char[] and Arrays.fill:

public static String repeatChar(char c, int count) { char[] chars = new char[count]; Arrays.fill(chars, c); return new String(chars); }

This works only for a single character, not for multi-character strings. Another option is Stream.generate with Collectors.joining, but it adds overhead and is less readable for this purpose.

Choosing Between String.repeat and a Loop

Use String.repeat(int) whenever you are on Java 11 or later. It is concise, well-tested, and avoids manual error handling. For older Java versions, a StringBuilder loop is the standard replacement.

The main decision is not performance—both approaches are linear in the output length—but compatibility and readability. If you are writing a library that must support Java 8, you cannot use repeat without a polyfill. In that case, a utility method with a loop is the pragmatic choice.

For single-character repetition, the char[] approach is slightly more efficient because it avoids the overhead of repeated append calls, but the difference is negligible for typical counts.

Performance and Memory Considerations

String.repeat creates a new string that is count times the length of the original. This requires memory proportional to the output size. For a string of length n repeated count times, the result uses n * count characters, each taking two bytes in the underlying byte[] (or one byte for Latin-1 strings).

Building the string with a StringBuilder that is pre-sized to the final length avoids intermediate allocations. String.repeat internally does something similar, so its memory behavior is comparable to a well-written loop.

A common mistake is to build a repeated string incrementally in a loop using + concatenation:

String result = ""; for (int i = 0; i < count; i++) { result += s; // creates a new string each iteration }

This is O(n²) in time and creates many intermediate strings, which is wasteful for large counts. Use StringBuilder or String.repeat instead.

For very large counts, be aware of the total output size. Repeating a 1 MB string 1000 times produces a 1 GB string, which can cause OutOfMemoryError. Always validate the count against expected limits in production code.

Common Use Cases for String Repeating

String repetition is useful in several scenarios:

  • Padding: Aligning text in console output or log messages by repeating spaces or dashes.
  • Indentation: Generating indentation levels for nested structures.
  • Test data: Creating large strings to test parsing, serialization, or network limits.
  • Separators: Producing a line of = or - to visually separate sections.
String separator = "-".repeat(80); System.out.println(separator);

For building a larger formatted output, you might combine repeat with String.format or StringBuilder to avoid excessive concatenation.

Edge Cases and Limitations

Beyond negative counts and null, consider the behavior with empty strings. "".repeat(100) returns an empty string, which is correct but can be surprising if you expected a repeated space. If you need a specific number of spaces, repeat " " instead.

Another limitation is that String.repeat works only with String, not with StringBuilder or StringBuffer. If you have a CharSequence, you must convert it to a String first.

Finally, the method is not static. You cannot call String.repeat("ab", 3); you must call "ab".repeat(3). This is a common source of confusion for developers new to the API.

When supporting multiple Java versions, you can write a compatibility wrapper that checks the Java version at runtime, but that adds complexity. In most cases, it is simpler to maintain a separate utility method for older versions and use repeat only when the target runtime guarantees Java 11+.

java string repeat: Practical Usage and Code Examples | RYUSLOG DEV