How do you left pad an integer value with zeroes in Java when converting to a string? This is a common requirement if you are working in finance domain. There are so many legacy systems out there which expect input of certain length, and if your input is shorter than specified length, you got to add zeros at the beginning of number to make them of right length. Java has rich API and thankfully neither
converting integer to String is difficult nor formatting String to add leading zeros. In fact there are multiple ways to add zeros at the start of a number or numeric String, you can either use powerful
String.format() method or it's close cousin
printf() method, or you can go back to
DecimalFormat class, if you are still working in JDK 4. Formatting in general is a very useful concept and as Java developer you must have a good understanding of that. Earlier we have learned about
formatting floating point numbers in Java and that knowledge is going to help a lot. There we have learned about using both
String.format() and
DecimalFormat to create floating point number up-to two, three or four decimal places, and if you have read that article then you are already familiar with tricky formatting instructions we pass to
format() method e.g.
"%07d", in this article we will learn how to left pad an integer value in Java by adding zeros at in front of the number.