How to add leading zeros with a number in java

Sometimes you need leading zero with number. Like you want a number with 4 digit width and you have a number with only single digit or less than 4 digits. Then leading zeros will be add to fill the space of missing digits.

String class has static method format() which does the same.

public class LeadingZero{
 public static void main(String args[]){  
   int n = 4;   
   String formattedNumber = String.format("%04d", n); 



Leave a Reply