Left pad and right pad a String in Java using Apache Commons

Sometimes you might need a fixed length string but the current value is much shorter so you need to fill out the string to a certain length. This is where the StringUtils class of the Apache Commons Lang library comes in handy with its methods leftPad() and rightPad().

There are three overloaded versions of each:

leftPad(String str, int size)
leftPad(String str, int size, char padChar)
leftPad(String str, int size, String padStr)

The first one takes the string to be padded and a size for the new padded string. The returned string will be padded on the left hand side with whitespaces. If the size is smaller than the original string, the original string will be returned.

The second one takes a padChar as a third parameter which simply means it will use that char instead of whitespaces for padding.

The third one takes a sequence of characters as third parameter and will use that whole string when padding. If the sum of padding characters is not divisible with the number of characters in the sequence the character sequence will simply be chopped at the right end.

There are corresponding methods for rightPad, which do exactly the same but on the right hand side of the string.

rightPad(String str, int size)
rightPad(String str, int size, char padChar)
rightPad(String str, int size, String padStr)

Below are a few examples of the leftPad methods:

The output from the above code is:

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

Please type any questions here.