Javaexercise.com

Java 11 String Repeat Method - Repeat String N Times

In Java 11, Java includes a new method repeat() into its String class. It is a utility method that is used to repeate the string specified number of times. It takes an integer argument and returns a string whose value is the concatenation of this string repeated count times.

 

Java String repeat() Syntax

public String repeat (int count)

 

  • It returns an empty string if count is zero or string is empty.

  • It takes integer type argument only.

  • If the count is negativeIllegalArgumentException is thrown.

  • It is added in Java 11 version.

 

Java String repeat() Method Example

Lets take an example to repeat a string "da" two times by using string repeat() method.

class Demo{
	public static void main(String[] args) {
		String str = "da";
		// Repeating string
		String newstr = str.repeat(2);
		System.out.println(newstr);
	}
}

Output:

dada

 

Example: If count is 0 (Zero)

If value of count is zero, then it returns an empty string as a result.

class Demo{
	public static void main(String[] args) {
		String str = "da";
		// Repeating string
		String newstr = str.repeat(0);
		System.out.println(newstr);
	}
}

 

 

Example: Empty String

If string is empty, then it returns empty string as a result.

class Demo{
	public static void main(String[] args) {
		// Empty String
		String str = "";
		// Repeating string
		String newstr = str.repeat(10);
		System.out.println(newstr);
	}
}

 

Example : Negative Count

If value of count argument is negative, then it throws an IllegalArgumentException.

class Demo{
	public static void main(String[] args) {
		String str = "da";
		// Repeating string with negative count
		String newstr = str.repeat(-1);
		System.out.println(newstr);
	}
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: count is negative: -1
 

 

Example: Alternate of String repeat method

If you are using Java version older than Java 11 then you can try this alternate way to repeat the string. In this example, we created a character array of count size (number of times repeatition) and then using replace() method, replaced all the default values of char array by the specified string. Lets see the below example.

class Demo{
	public static void main(String[] args) {
		String str = "da";
		// Create a string using char array
		String str2 = new String(new char[2]);
		// Replace char array elements by string
		String newstr = str2.replace("\0", str);
		System.out.println(newstr);
	}
}

 

Output:

dada
 


Conclusion

Well, in this topic, we learnt about the new repeat() method of String class. We discussed various scenarios by using examples and alternate way to repeat string in case Java version is older that 11.

If we missed something, you can suggest us at - info.javaexercise.com