Read Also: Generate random hex color in Java with source code
Note: We can also achieve our goal with the help of leftPad() and rightPad() StringUtils class methods provided by the Apache Commons library. If the library is in classpath, use leftPad() and rightPad() methods as they are more convenient, readable and you don't need to remember different String formatting options to left and right pad a String with zero or any character.
How to get integer with 0 filled in front in Java
Below is the simple Java program for left padding with 0:public class LeftPaddingExample { public static void main(String args[]) { int givenNumber = 6; /* In the below line we are left padding givenNumber with four zeros where, % represents formatting starts 0 represents the character we want to leftpad 5 represents the result should be 5 characters in size d represents the input will be a decimal integer */ String leftPadded = String.format("%05d", givenNumber); System.out.println("LeftPadded given number: " + leftPadded); // Another example of left padding zeros /* In the below line we are left padding givenNumber with two zeros where, % represents formatting starts 0 represents the character we want to leftpad 3 represents the result should be 3 characters in size d represents the input will be a decimal integer */ String leftPadded2 = String.format("%03d", givenNumber); System.out.println("LeftPadded given number 2nd time: " + leftPadded2); } }
Output:
LeftPadded given number: 00006
LeftPadded given number 2nd time: 006
That's all for today. Please mention in the comments if you have any questions related to how to get an integer with 0 filled in front in Java.