Java String.repeat
Repeat a string a nonnegative number of times and return the combined text.
A simple example
String.repeat
- Start with "a", count 3
- Do this Repeat the text
- Result "aaa"
class Main {
public static void main(String[] args) throws Exception {
System.out.println("a".repeat(3));
}
}
aaa
Syntax
public String repeat(int count)
JDK 21 method signatures (1)
public String repeat(int count)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaDraw a divider on a receipt
A receipt printer needs a divider that spans a fixed number of columns. Repeat the chosen mark to the required width so the checkout layout can change without editing a long literal string.
class Main {
public static void main(String[] args) throws Exception {
System.out.println("-".repeat(8));
}
}
--------
Eight copies form the divider.
Make a small attendance chart
A small text-only display uses a repeated mark to represent a divider or a count. Generate the marks from the requested number so the visual result grows or shrinks with the input.
class Main {
public static void main(String[] args) throws Exception {
int students = 3;
System.out.println("■ ".repeat(students).stripTrailing());
}
}
■ ■ ■
One block represents each student in the group.
Mark a workshop attendance card
A student attends three workshop sessions. The card printer repeats one mark for every earned stamp. What strip appears on the card?
What to watch for
Zero repetitions produce an empty string. Reject negative or unreasonably large counts before allocating output.