How to repeat String N times in Java

In this post, we are going to repeat a string N time using Java code. While working with string there can be a need of repeating a string, for that purpose, Java provides repeat() method in String class.

The repeat() method is added in the String class from Java 11 version.

There are several ways to repeat to a string like using nCopies() method of Collections class or repeat() method or replace() method of string can also be used to get repeat string.

Time for an Example: Java 11

Let's create an example to repeat a string. Here, we are using the repeat() method of the String class. It is the simplest way to repeat the string. This method is added to the String class with the Java 11 version.

public class Main {
	public static void main(String[] args){
		String str = "Studytonight";
		System.out.println(str);
		// Repeat String
		String newStr = str.repeat(3);
		System.out.println(newStr);
	}
}


Studytonight
StudytonightStudytonightStudytonight

Example: Repeating using String Constructor and replace() Method

Let's create an example, to repeat string in Java. Here, we are using replace() method that is used to replace string but with some logical code, we can use it to repeat string. Here, we are creating a string using a char array and replacing the array's default value by the provided string.

public class Main {
	public static void main(String[] args){
		String str = "Studytonight";
		System.out.println(str);
		// Repeat String
		String newStr = new String(new char[3]).replace("\0", str);
		System.out.println(newStr);
	}
}


Studytonight
StudytonightStudytonightStudytonight

Example: Repeat String using Java 8

If you are using Java 8 or higher version then you can use nCopies() method of Collections class that is joined into the string using the join() method of String class.

import java.util.Collections;

public class Main {
	public static void main(String[] args){
		String str = "Studytonight";
		System.out.println(str);
		// Repeat String
		String newStr = String.join("", Collections.nCopies(3, str));
		System.out.println(newStr);
	}
}


Studytonight
StudytonightStudytonightStudytonight