This post will discuss how to add padding to a String in Java.

1. Using String.format() method

A common solution to left/right pad a string with spaces is using the String.format() method. For example,

Download  Run Code

 
If your string is numeric, you can pad it with zeros by converting it to an integer:

Download  Run Code

2. Using Apache Commons StringUtils class

Alternatively, you can leverage Apache Commons Lang’s StringUtils class leftPad() and rightPad() utility methods, which can add specified padding to the start and end of a string, respectively.

Download Code

3. Using Guava

You can also leverage padStart() and padEnd() method offered by Guava’s Strings class. The method signature remains the same as the above solution.

Download Code

That’s all about padding a String in Java.