Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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

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

~4 min readJava
#Java#String#Java 11#StringBuilder
Illustration of Java string repeat concept with a repeated character sequence.

To repeat a string in Java, use the String.repeat(int count) method on Java 11 and later. For older Java versions, use a StringBuilder loop or a small utility method. Repeating strings is a common operation for padding, formatting, or generating test data, so it helps to know both the built-in approach and the fallbacks.

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

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

java
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 string content, 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.
java
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 operation does not modify the original string, which is consistent with Java's immutable String design. If count is 1, the implementation may return the same instance, but treating the result as a read-only string is safe.

Repeating a String Before Java 11

If your project uses a Java version before 11, String.repeat is not available. You have several manual approaches. The most straightforward is a StringBuilder loop:

java
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:

java
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

The result length is count times the length of the original, so memory usage is proportional to the output size. For a string of length n repeated count times, the result contains n * count characters. Modern Java implementations may store Latin-1 strings with one byte per character and other strings with two bytes per character, so memory use depends on the content.

Building the string with a StringBuilder that is pre-sized to the final length avoids intermediate allocations. The built-in method also avoids the repeated intermediate strings you would get from + concatenation, 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:

java
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.
java
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+.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.