Java String Handling

Create string with specified number of characters example

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

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

There are several ways using which you can create string with 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 version, use StringBuffer instead of StringBuilder class.

2) Using fill method of Arrays class

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

Output

3) Using replace method of String class

Create a char array of fixed length and create a new String from it using 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 repeat method of 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 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

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

 

Join 1000+ fellow learners! Enter your email address below: