Member-only story

Java String.repeat(): The Best Way to Repeat Strings Without Loops

Learn how Java’s String.repeat() method simplifies text repetition without loops.

Ramesh Fadatare

--

🚀 Introduction: Why Use String.repeat()?

Before Java 11, repeating a string required manual loops or StringBuilder, making the code:
Verbose – Multiple lines for simple text repetition
Inefficient – Creating unnecessary loop iterations
Harder to read

💡 Java 11 introduced String.repeat(n), which provides a cleaner, faster, and more readable way to repeat text.

📌 In this article, you’ll learn:
✅ Why String.repeat() is better than loops
✅ How to use repeat(n) with complete examples
✅ Performance benefits compared to traditional loops

🔍 The Problem: Repeating Strings Before Java 11

✔ Using a for Loop (Old Approach)

public class RepeatUsingLoop {
public static void main(String[] args) {
String text = "Hello ";
String result = "";

for (int i = 0; i < 5; i++) { // Repeat 5 times
result += text;
}

System.out.println(result);
}
}

--

--

No responses yet