String.repeat()
Code Comparison
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
sb.append("abc");
}
String result = sb.toString();
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
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.
Related Documentation
Proof