forked from javaevolved/javaevolved.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring-repeat.yaml
More file actions
46 lines (46 loc) · 1.34 KB
/
string-repeat.yaml
File metadata and controls
46 lines (46 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
---
id: 31
slug: "string-repeat"
title: "String.repeat()"
category: "strings"
difficulty: "beginner"
jdkVersion: "11"
oldLabel: "Java 8"
modernLabel: "Java 11+"
oldApproach: "StringBuilder Loop"
modernApproach: "repeat()"
oldCode: |-
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
sb.append("abc");
}
String result = sb.toString();
modernCode: |-
String result = "abc".repeat(3);
// "abcabcabc"
summary: "Repeat a string n times without a loop."
explanation: "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."
whyModernWins:
- icon: "📏"
title: "One-liner"
desc: "Replace 5 lines of StringBuilder code with one call."
- icon: "⚡"
title: "Optimized"
desc: "Internal implementation is optimized for large repeats."
- icon: "📖"
title: "Clear intent"
desc: "repeat(3) immediately conveys the purpose."
support:
state: "available"
description: "Widely available since JDK 11 (Sept 2018)"
prev: "strings/string-strip"
next: "strings/string-indent-transform"
related:
- "strings/string-isblank"
- "strings/string-formatted"
- "strings/string-chars-stream"
docs:
- title: "String.repeat()"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/String.html#repeat(int)"