Wednesday, July 28, 2021

How to Add Leading Zeros to Integers in Java ? String Left Padding Example Program

Hello guys, you may know that from Java 5 onwards it's easy to left pad Integers with leading zeros when printing number as String. In fact, You can use the same technique to left and right pad Java String with any characters including zeros, space. Java 5 provides String format methods to display String in various formats. By using the format() method we can add leading zeros to an Integer or String number. By the way, this is also known as left padding Integers with zero in Java. For those who are not familiar with the left and right padding of String, here is a quick recap;

When we add characters like zero or space on left of a String, its known as left padding and when we do the same on the right side of String, it's known as right padding of String. This is useful when you are displaying currency amounts or numbers, which has fixed width, and you want to add leading zeros instead of space in front of Integers.

If by any chance, You are not using Java 5 or you like to use open source projects like Apache commons, Google Guava or Spring framework then you can use leftPad() and rightPad() methods provided by StringUtils class. I personally prefer JDK function if it provides required functionality but It's very common to have Spring, Apache commons or Guava already in your classpath

In that case use those method because 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 . By the way, while padding String and number left and right, it's worth remember not to right pad numbers with zero, it will completely change there meaning.



Left and Right padding Integer and String in Java

How to add leading zeros to Integer in Java - String left padding exampleIn this Java tutorial, we will see How to add leading zero to Integer or String in Java. Both are actually same because you only print String in Java and left padding is done at the time of display and the original Integer value is not affected. The format() method of String class in Java 5 is the first choice. You just need to add "%03d" to add 3 leading zeros in an Integer. Formatting instruction to String starts with "%" and 0 is the character which is used in padding. By default left padding is used, 3 is the size and d is used to print integers. 

It means if the number has 1 or 2 digits than some leading zeros will be added to the number to make its width equal to 3. This is also known as left padding of Integers in Java. By default Java left pad with space and if you add 0 then Integer will be left padded with zero. You can not use other character e.g. # here. 

On the other hand both Spring and Apache commons StringUtils provides you convenient leftPad() and rightPad() method to add left and right padding on String in Java. These methods also allow you to pass any character of your choice to be used as padding e.g. zero, # or space.




Java String left and right padding example

Let's see some code example of left and right padding String and Integer in Java using Spring, Apache Commons StringUtils and format method of String.

import java.util.logging.Logger;
import org.apache.commons.lang.StringUtils;

/**
 * Java program to show How to add leading zeros in Integer or String in Java.
 * This Java examples shows 3 ways to add left padding of any character including zero
 * to an integer or String in Java. This program uses Java 5 String.format(), Apache
 * commons StringUtils leftPad() and Spring Framework StringUtil's leftpad() method
 * to add zeros in front of a number in Java.
 *
 * @author http://javarevisited.blogspot.com
 */
public class StringPadding {
    private static final Logger logger = Logger.getLogger(StringPadding.class.getName());
   
    public static void main(String args[]) {
      
        int number = 7;
      
        //add 3 leading zeros in this number
        String padded = String.format("%03d" , number);
        System.out.println("Integer number left padded with zero : " + padded);
      
        //left pad 7 zeros in this integer
        padded = String.format("%07d" , number);
        System.out.println("Java example to add leading zeros in Integer : " + padded);
      
        //left padding String with zeros using Spring framework StringUtils class
        String leftPadded = StringUtils.leftPad("" + number, 7, "0");
        System.out.println("Adding zeros in front of String using Spring - left padding : " + leftPadded);
      
        //Adding leading zeros in a number using Apache commons StrigUtil class
        String leadingZero = org.apache.commons.lang.StringUtils.leftPad("" +8, 7, "#");
        System.out.println("Adding leading zeros to String in Java using Apache commons : " + leadingZero);
   
        //how to right pad String in Java with any character
        String rightpadded = StringUtils.rightPad("7", 7, "#");
        System.out.println("Right padded String in Java with #: " + rightpadded);
      
        //right padding String in Java using Apache commons lang StringUtils class
        String rPadded = org.apache.commons.lang.StringUtils.rightPad("9", 7, "#");
        System.out.println("Right padding String with any char in Java : " + rPadded);
      
        //Java 5 String format method can use to right padding String with space
        String str = String.format("%-7d", 7);
        System.out.println("Right pad Integer using Java 5 format method : " + str);
    }
  
}

Output:
Integer number left padded with zero : 007
Java example to add leading zeros in Integer : 0000007
Adding zeros in front of String using Spring - left padding : 0000007
Adding leading zeros to String in Java using Apache commons : ######8
Right padded String in Java with #: 7######
Right padding String with any char in Java : 9######
Right pad Integer using Java 5 format method : 7

All the examples are self-explanatory, except the String format option, which I have explained in an earlier section. If you just want to left or right pad String in Java and happen to use Spring or Apache commons then use leftPad() and rightPad() method, those are easy to use and much readable than the format method of String.

That's all on how to add leading zeros to Integer in Java or How to add left and right padding String in Java. As I said you can either use format() method or java.lang.String or StringUtils from Apache commons and  Spring framework to left or right pad a Java String. Looks like both Spring and Apache commons StringUtils provide identical API for left and right padding String with any character.


3 comments :

Geeta said...

I wouldn't suggest using third party library like Spring or Apache commons, if you add leading zeros into a number so easily by using format() method of java.lang.String. Depending only upon core Java library is good strategy and can prevent lots of issues related to dependency management and classpath configuration.

Unknown said...

How can i print 0200, 0330 using for loop in java.

Class Notes said...

result should be in int not in string value then how we will do ?
result (int i)
i=01 //output

Post a Comment