🚀 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);
}
}
📌 Problems:
❌ Creates unnecessary intermediate strings (result += text
is inefficient)
❌ Concatenation inside a loop is slow
❌ Not the best practice for performance
✔ Using StringBuilder
(More Efficient but Still Verbose)
public class RepeatUsingStringBuilder {
public static void main(String[] args) {
String text = "Hello ";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) {
sb.append(text);
}
System.out.println(sb.toString());
}
}
📌 Problems:
❌ More efficient than +=
, but still uses loops
❌ Extra boilerplate (StringBuilder
and loop code)
✅ The Best Solution: Using String.repeat(n)
1️⃣ Simple Example: Repeating Text
public class RepeatUsingStringRepeat {
public static void main(String[] args) {
String text = "Hello ";
String result = text.repeat(5); // Repeat 5 times
System.out.println(result);
}
}
📌 Why is this better?
✅ Cleaner syntax – No loops, no extra variables
✅ Faster execution – Optimized internally by Java
✅ More readable – text.repeat(5)
clearly conveys the intent
2️⃣ Using repeat()
for Pattern Generation
String.repeat()
is perfect for generating text-based patterns.
public class StringRepeatPatterns {
public static void main(String[] args) {
System.out.println("*".repeat(10)); // Line of 10 asterisks
System.out.println("=".repeat(20)); // Line of 20 equal signs
}
}
3️⃣ Using repeat()
to Format Indentation
repeat()
can generate dynamic spaces or indentations.
public class RepeatIndentation {
public static void main(String[] args) {
int level = 3;
String indent = " ".repeat(level); // Indent using spaces
System.out.println(indent + "Indented Text");
}
}
📌 Output:
Indented Text
✅ Perfect for hierarchical text displays (logs, JSON, XML formatting, etc.)
4️⃣ Combining repeat()
with Streams for Multi-Line Output
import java.util.stream.IntStream;
public class RepeatWithStreams {
public static void main(String[] args) {
IntStream.range(1, 6).forEach(i ->
System.out.println("*".repeat(i)) // Pyramid pattern
);
}
}
📌 Output:
*
**
***
****
*****
✅ Combining repeat()
with Streams makes complex text patterns easier!
🚀 Performance Comparison: repeat()
vs Loops
Method | Performance | Code Readability | Best Use Case |
---|---|---|---|
for loop with += |
❌ Slow (Creates many intermediate strings) | ❌ Messy | Avoid using |
StringBuilder.append() |
✅ Faster (Reduces intermediate objects) | ❌ Verbose | When loops are required |
String.repeat(n) |
🚀 Fastest (Optimized in Java) | ✅ Clean & Simple | Best for text repetition |
📌 String.repeat(n)
is the fastest and cleanest way to repeat text in Java!
🔥 When to Use String.repeat()
Instead of Loops?
Use Case | Use repeat() ? |
Use Loops? |
---|---|---|
Basic string repetition | ✅ Yes | ❌ No |
Generating separators ("=====" ) |
✅ Yes | ❌ No |
Creating text-based patterns | ✅ Yes | ❌ No |
Repeating complex objects | ❌ No | ✅ Yes |
Repeatedly modifying a string | ❌ No | ✅ Yes |
🚀 Use String.repeat(n)
whenever you need to repeat simple text!
🔑 Key Takeaways
✅ Java 11’s String.repeat(n)
simplifies text repetition.
✅ Removes the need for loops or StringBuilder
for simple cases.
✅ More efficient, faster, and readable than manual loops.
✅ Works great for patterns, indentation, and UI formatting.
By switching to repeat(n)
, your Java code will be cleaner, faster, and easier to maintain! 🚀
Comments
Post a Comment
Leave Comment