repeat() method in Java 11

repeat() method is present in String class of Java 11. It is used to repeat the string by the number of times mentioned in the argument of method and concatenate it at end of string.

repeat() takes an argument which is an integer number that signifies the number of times the string is to be repeated. If the string is empty then an empty string is returned

Let us look at an example code :

public class RepeatExample {

	public static void main(String[] args) {
		
		String str1 = "Tech4Humans";
		str1 = str1.repeat(2);
		System.out.println(str1);
		
	
		// empty string
		String str3 = "";
		str3 = str3.repeat(3);        //empty string is returned
		System.out.println(str3);   
		
		
		String str2 = " Great ";
		str2 = str2.repeat(3);
		System.out.println(str2);


	}
}

Output

Tech4HumansTech4Humans

 Great  Great  Great 

Leave a Comment