String repeat() – Repeat string N times in Java

Lokesh Gupta

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 !!

Comments

Subscribe
Notify of
guest
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

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.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode