Practical Uses of repeat: Formatting and Padding
What you'll learn: How to apply the repeat() method to create formatted console output with horizontal rules, indentation, and fixed-width padding.
Now that you know repeat() duplicates strings, let's see where it shines in real-world formatting tasks. Think of repeat() as your tool for creating visual structure—like using a ruler to draw straight lines or a stamp to create uniform spacing.
Creating Horizontal Rules
Horizontal rules help separate sections in console output:
String rule = "-".repeat(50);
System.out.println(rule);
System.out.println("Important Section");
System.out.println(rule);
This creates a clean 50-character separator line—far simpler than manual string building.
Dynamic Indentation
Create indentation strings for nested structures or hierarchical displays:
int level = 3;
String indent = " ".repeat(level); // Two spaces per level
System.out.println(indent + "Nested item at level " + level);
This is perfect for tree-like output, JSON formatting, or representing depth in recursive structures.
Fixed-Width Padding
Pad strings to align columns in tables:
String name = "Alice";
String paddedName = name + " ".repeat(15 - name.length());
System.out.println(paddedName + "| Score: 95");
This creates uniform column widths by filling the gap with spaces. You can combine it with substring() to enforce maximum widths while padding minimums.
Combining Techniques
String header = "REPORT";
String border = "=".repeat(40);
String padding = " ".repeat((40 - header.length()) / 2);
System.out.println(border);
System.out.println(padding + header);
System.out.println(border);
This centers a header within a bordered box—clean, readable, and maintainable.
Key Takeaway: Use repeat() to generate horizontal rules, dynamic indentation strings, and fixed-width padding, transforming messy concatenation loops into clear, one-line formatting solutions.