How to format a Java string with leading zero?

Roy picture Roy · Oct 29, 2010 · Viewed 314.1k times · Source

Here is the String, for example:

"Apple"

and I would like to add zero to fill in 8 chars:

"000Apple"

How can I do so?

Answer

Alex Rashkov picture Alex Rashkov · Oct 29, 2010
public class LeadingZerosExample {
    public static void main(String[] args) {
       int number = 1500;

       // String format below will add leading zeros (the %0 syntax) 
       // to the number above. 
       // The length of the formatted string will be 7 characters.

       String formatted = String.format("%07d", number);

       System.out.println("Number with leading zeros: " + formatted);
    }
}