This post will discuss how to format a string with leading zeros in Java.

1. Using String.format() method

The standard solution to format a string is to use the String.format() method, which takes printf-style format strings. To get a zero-padded string, you can use the '0' flag with width indicating the minimum number of characters to be written to the output.

Download  Run Code

Output:

0000000001011101

2. Using Apache Commons Lang

Apache Commons Lang StringUtils utility class provides the leftPad() method that can left-pad a string with the specified character. You can use it as follows:

Download Code

Output:

0000000001011101

3. Using Guava Libaray

Guava’ Strings utility class provides the padStart() method that prepends a String with copies of the specified character to reach the specified length. You can use it as follows:

Download Code

Output:

0000000001011101

That’s all about formatting a string with leading zeros in Java.