String repeat() – Repeat string N times in Java

Learn to repeat a given string N times, to produce a new string which contains all the repetitions, though a simple Java program using String.repeat() api.

Java 11

Learn to repeat a given string N times, to produce a new string which contains all the repetitions, though a simple Java program. We will use method Sting.repeat(N) (since Java 11) and using regular expression which can be used till Java 10.

1. String.repeat() API [Since Java 11]

This method returns a string whose value is the concatenation of given string repeated count times. If the string is empty or count is zero then the empty string is returned.

1.1. Syntax

/**
* Parameters:
* count - number of times to repeat
* 
* Returns:
* A string composed of this string repeated count times or the empty string if this string is empty or count is zero
* 
* Throws:
* IllegalArgumentException - if the count is negative.
*/

public String repeat​(int count)

1.2. Example

Java program to repeat string ‘Abc’ to 3 times.

public class Main 
{
	public static void main(String[] args) 
	{
		String str = "Abc";

		System.out.println( str.repeat(3) );
	}
}

Program output.

AbcAbcAbc

2. Repeat string using regex [till Java 10]

If you are working on JDK <= 10, then you may consider using regex to repeat a string N times.

Java program to repeat string ‘Abc’ to 3 times.

public class Main 
{
	public static void main(String[] args) 
	{
		String str = "Abc";

		String repeated = new String(new char[3]).replace("\0", str);

		System.out.println(repeated);
	}
}

Program output.

AbcAbcAbc

3. Apache Common’s StringUtils class

If regex is not what you are looking for – then you can use StringUtils class and it’s method repeat(times).

import org.apache.commons.lang3.StringUtils;

public class Main 
{
	public static void main(String[] args) 
	{
		String str = "Abc";
	
		String repeated = StringUtils.repeat(str, 3);

		System.out.println(repeated);
	}
}

Program output.

AbcAbcAbc

Drop me your questions related to how to repeat a string N times in Java.

Happy Learning !!

Leave a Comment

  1. Are you saying that regex can be used for jdk <=14, but it is recommended only if jdk <= 10, since 'repeat's is avail in jdk 11?

    How you wrote this implies jdk 11 will not work for regex.
    "If you are working on JDK <= 10, then you may consider using regex to repeat a string N times."

  2. What is the solution, when the n times is of data type Long. The above mentioned methods are not supporting long data type. Only int data types are supported. Can you help me with this.

Comments are closed.

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.