How to repeat a string multiple times in Java?

In this post, we will describe how to repeat a string multiple times in Java. To do this, we will use Apache Commons library.

Requirement:

I have the following word.."Six". ( without quotes). I want to construct, SixSixSixSixSix..(i.e. the word repeated 5 times). How to do this in Java?

JAR Files:

Let us do less coding to accomplish this. So, download commons-lang3-3.1.jar and make sure you have it in your classpath.

Solution:

The Java code is given below:

import org.apache.commons.lang3.StringUtils; // to repeat the string
public class repeatString {    
    public static void main (String[] args) {
                        String myInput="Six";
                        String newRepeatedString=StringUtils.repeat(myInput,5);
 //we repeated the string 5 times
                        System.out.println("Input String: " + myInput);
                        System.out.println("Repeated String: " + newRepeatedString);                    
    }
}

Compile / Run the Code


Compiling and executing the code produces the output we are looking for:

C:\Java\commons-lang3-3.1>javac -classpath .;commons-lang3-3.1.jar repeatString.
java
C:\Java\commons-lang3-3.1>java -classpath .;commons-lang3-3.1.jar repeatString
Input String: Six
Repeated String: SixSixSixSixSix
C:\Java\commons-lang3-3.1>



See you in a different tutorial next time.