How to repeat string n times in java?

Suppose you have the string ‘qwe’ and you need to repeat string ‘n’ times. Here’s how to do it:

Using java 8 stream api

Using String.format

Let us examine this example in more detail. Primitive types ( char[] , in this case) are instantiated with nulls “number of times”, then a String is created from the char[] , and the nulls are replaced() with the original string str.

Using StringBuilder and loop

And last but not least, you can use StringBuilder and loop

Using third-party libraries

You could use Apache commons-lang (which has an impressive collection of handy string utilities):

 

 

 

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.