Library contents

Java String.repeat

Repeat a string a nonnegative number of times and return the combined text.

A simple example

String.repeat

  1. Start with "a", count 3
  2. Do this Repeat the text
  3. Result "aaa"
Three copies are placed next to one another.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("a".repeat(3));
    }
}
Output
aaa

Syntax

Java 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.java

Draw 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.

Result--------
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("-".repeat(8));
    }
}
Output
--------

Eight copies form the divider.

Advertisements

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.

From the programint students = 3
Result■ ■ ■
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        int students = 3;
        System.out.println("■ ".repeat(students).stripTrailing());
    }
}
Output
■ ■ ■

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?

Given3 sessions · mark *
Worked result***

What to watch for

Zero repetitions produce an empty string. Reject negative or unreasonably large counts before allocating output.

Documentation for String.repeat