In this post, we will learn “How to repeat a string N number of times in Java 11?”. Java 11 introduced a new method called repeat(N) to do that.
Here, we are going to learn following things:
- What is repeat(N) method?
- How to use it?
How to Repeat String in Java 11?...!!! Share on X
Let’s Begin,
1. What is repeat(N) method?
repeat(N) is a string method of String class.
This method returns a string whose value is the concatenation of this string repeated count times. If this string is empty or count is zero then the empty string is returned.
Syntax:
/**
* @param count number of times to repeat
*
* @return A string composed of this string repeated
* {@code count} times or the empty string if this
* string is empty or count is zero
*
* @throws IllegalArgumentException if the {@code count} is
* negative.
*
* @since 11
*/
public String repeat(int count)
2. How to use it?
Let’s take an example where we are repeating a word ‘Techndeck’ 5 times.
public class Repeat_String_Java11 {
public static void main(String[] args) {
var S = "Techndeck";
//Repeat the above string 5 times using Java 11
var newS = S.repeat(5);
System.out.println("Value of the newS is: " + newS);
}
}
Output:
Value of the newS is: TechndeckTechndeckTechndeckTechndeckTechndeck
How to Repeat String in Java 11?...!!! Share on X
Do you like this Post? – then check my other helpful posts: