This post will discuss how to left pad an integer with zeros in Java.

1. Using String.format() method

The String.format() method returns a formatted string using the specified format string. You can provide the '0' flag, which causes the output to be padded with leading zeros until the length of the string is equal to the desired field width. This is demonstrated below:

Download  Run Code

Output:

00125

2. Using PrintStream#printf() method

Alternatively, if you need to write the padded output to the output stream, you can do so using the PrintStream#printf() method. It accepts a format string with the '0' flag, similar to the String.format() method.

Download  Run Code

Output:

01024

3. Using DecimalFormat.format() method

Another option is to create a DecimalFormat using a pattern consisting of all zeros. The number of zeros in the pattern string should be equal to the desired field width.

Download  Run Code

Output:

00111

4. Using Apache Commons Lang

You can also use the StringUtils.leftPad() method from Apache Commons Lang Library to pad an integer with leading zeros to a specific length.

Download Code

Output:

00001

5. Using Guava

If you prefer Guava to Apache Commons Lang, you can use the padStart() method from the Strings class to get a left padded string as shown below:

Download Code

Output:

0125

That’s all about left padding an integer with zeros in Java.