String.repeat()
Repeat a string n times without a loop.
Code Comparison
✕ Java 8
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
sb.append("abc");
}
String result = sb.toString();
✓ Java 11+
String result = "abc".repeat(3); // "abcabcabc"
Why the modern way wins
One-liner
Replace 5 lines of StringBuilder code with one call.
Optimized
Internal implementation is optimized for large repeats.
Clear intent
repeat(3) immediately conveys the purpose.
Old Approach
StringBuilder Loop
Modern Approach
repeat()
Since JDK
11
Difficulty
beginner
JDK Support
String.repeat()
Available
Widely available since JDK 11 (Sept 2018)
How it works
String.repeat(int) returns the string concatenated with itself n times. Handles edge cases: repeat(0) returns empty string, repeat(1) returns the same string.