Java 25 (LTS) reference · String Methods

Java String repeat() Method

Return the string repeated n times. Handy for padding, separators and simple text art.

Java 25 (LTS) Since Java 11

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

string.repeat(count)

Parameters

ParameterDescription
count
int
How many times (0 gives an empty string).

Return value

A new String.

Examples

Repeat text
public class Main {
    public static void main(String[] args) {
        System.out.println("-".repeat(20));
        System.out.println("ab".repeat(3));
    }
}

Output

--------------------
ababab

Run this on your computer — see “Get Started” for setup.

A small triangle
public class Main {
    public static void main(String[] args) {
        for (int i = 1; i <= 4; i++) {
            System.out.println(" ".repeat(4 - i) + "*".repeat(2 * i - 1));
        }
    }
}

Output

   *
  ***
 *****
*******

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 11Added

Was this page helpful?