Center a String within another String in Java

Using the StringUtils class in the Apache Commons Library we can center a String within a new created String by calling the center() method of the StringUtils class. The new String returned will be filled with blank characters on both sides of the centered value.

In the example below we have a String value with the initial length of 10. We call center with that value and specify the new String length to 20 which means it will put 5 blank characters on each side. Finally we print out the new String using a dash before and after to make it more visible, and also print out the length of the new String.


There are also two overloaded center() methods that also takes a padding character as parameter (either as a char or a String). In the below code we add that padding character as an asterisk.

and output from the above code:

Search for more Java info on this site here:
Custom Search

Please type any questions here.