How to get integer with 0 filled in front in Java

In this post, I will share how to get integer with 0 (zero) filled in front in Java with examples. In other words, this is also known as left padding integers with zero in Java. We can easily achieve our goal with the help of the String class format() method. This method was introduced in Java 5.

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.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry