The repeat Method: Duplicating Strings
What you'll learn: How to use repeat(n) to create multiple copies of a string in a single method call.
What is repeat()?
The repeat(int count) method (introduced in Java 11) creates a new string by concatenating the original string count times. Instead of writing loops or using StringBuilder to duplicate a string, you can simply call repeat() with the number of repetitions you need.
Think of it like a copy-paste command that automatically pastes your text exactly n times.
How It Works
String dash = "-";
String line = dash.repeat(20); // "--------------------"
String hello = "Hello";
String repeated = hello.repeat(3); // "HelloHelloHello"
If you pass 0 as the count, you get an empty string. If you pass 1, you get the original string (technically a copy, since strings are immutable).
String word = "Java";
System.out.println(word.repeat(0)); // ""
System.out.println(word.repeat(1)); // "Java"
Common Use Cases
Padding and formatting:
String header = "Report";
String border = "=".repeat(40);
System.out.println(border);
System.out.println(header);
System.out.println(border);
Creating indentation:
int indentLevel = 3;
String indent = " ".repeat(indentLevel); // 6 spaces total
System.out.println(indent + "Nested item");
Generating patterns:
String stars = "*".repeat(5); // "*****"
String spaces = " ".repeat(10);
Edge Cases
Passing a negative number throws an IllegalArgumentException. The method is far more readable and efficient than manually looping to build repeated strings.
Key Takeaway: Use repeat(n) to cleanly duplicate a string n times—perfect for padding, patterns, and formatting tasks without manual loops or StringBuilder.