Skip to content

Create string with specified number of characters example

Create string with the specified number of characters example shows how to create string with n number of characters. The example also shows how to create fixed length string by repeating given character.

How to create a string with the specified number of characters in Java?

There are several ways using which you can create a string with the specified number of characters as given below.

1) Using StringBuilder/StringBuffer

You can use a loop and StringBuilder class to append the specified character number of times to create a fixed length string as given below.

Output

Note: If you are using Java 1.4 or earlier versions, use the StringBuffer instead of the StringBuilder class.

2) Using the fill method of Arrays class

Create a char array and fill it with the character you want using fill method of the Arrays class. Finally, convert the character array to a string using the String constructor.

Output

3) Using the replace method of String class

Create a char array of fixed length and create a new String from it using the constructor to get the String of required length. Finally, replace all null characters (represented by ‘\0’) with the character of your choice.

Output

4) Using the repeat method of the Apache Commons library

If you are using Apache commons library, you can use repeat method of StringUtils class to create a fixed length string with the specified character.

This method creates a new string by repeating specified character n times. You can also use overloaded repeat method that accepts String instead of character.

Output

This example is a part of the Java String tutorial with examples.

Please let me know your views in the comments section below.

About the author

2 comments

Leave a Reply

Your email address will not be published.