Java Language Repeat a String n times


Example

Problem: Create a String containing n repetitions of a String s.

The trivial approach would be repeatedly concatenating the String

final int n = ...
final String s = ...
String result = "";

for (int i = 0; i < n; i++) {
    result += s;
}

This creates n new string instances containing 1 to n repetitions of s resulting in a runtime of O(s.length() * n²) = O(s.length() * (1+2+...+(n-1)+n)).

To avoid this StringBuilder should be used, which allows creating the String in O(s.length() * n) instead:

final int n = ...
final String s = ...

StringBuilder builder = new StringBuilder();

for (int i = 0; i < n; i++) {
    builder.append(s);
}

String result = builder.toString();