String repeat method

1. Introduction

Sometimes you might need to repeat a string certain number of times. In such case, you can use String class repeat() method.

The signature of repeat method is:

public String repeat​(int count)This method returns a string whose value is the concatenation of this string repeated count number of times. If this string is empty or count is zero then the empty string is returned.

The repeat() method was added in Java 11.

2. Example

public class RepeatMethodExample {
    public static void main(String args[]) {
        //when input string is not empty
        String s1 = "abc";
        String repeatedString1 = s1.repeat(3);
        System.out.println("repeatedString1: " + repeatedString1);
        System.out.println("repeatedString1.length(): " + repeatedString1.length());

        //when input string is empty
        String s2 = "";
        String repeatedString2 = s2.repeat(3);
        System.out.println("repeatedString2: " + repeatedString2);
        System.out.println("repeatedString2.length(): " + repeatedString2.length());


repeatedString1: abcabcabc
repeatedString1.length(): 9
repeatedString2.length(): 0

3. Conclusion

In conclusion, the repeat() method provides a concise and efficient way to generate a new string by repeating the original string a specified number of times. Through this tutorial, we’ve explored its syntax, usage, and various examples to demonstrate its versatility in different scenarios. Whether you’re creating formatted strings, generating patterns, or simplifying repetitive tasks, the repeat() method proves to be a valuable tool in your arsenal. By leveraging this method effectively, you can streamline your code, improve readability, and enhance your overall programming experience.