Skip to content

Java String pad with zero example

Java String pad with zero example shows how to left pad or right pad string with zero in Java. The example also shows how to left pad string with zero, right pad string with zero using various ways.

How to pad a string with zero in Java?

There are various ways using which you can pad a string with zero in Java as given below.

1) Using the substring method

The substring method of String class can be used to pad string with zero as given below.

Output

The above approach does not use any external library to pad string. We first stored the required string length and pad characters. For padding left with zeros, we first took a substring from the padding character string starting from index equal to the string size we want to pad, which gave us (required length – string length) pad characters.

For example, if our string is 4 characters, substring will give us 6 zeros (10 – 4). We then concatenate the padding string and original string which gave us padded string with zero.

You can change the required length and pad character string as per your requirements.

2) Using String format (Java 1.5 and above)

String class in Java 1.5 introduced a new method named format which can be used to pad the string with zeros. The format method can make a string of required length by adding spaces either on the left or the right side of the String. You can replace the spaces with zeros to left pad or right pad string with zeros as given below.

Output

The above example uses 10 as the desired length and zeroes as a padding character. You may change both of them according to your needs.

Important Note: This approach does not work if the original string already contained spaces. We are replacing all the spaces with zeros, so if String had spaces in it, they would also be replaced.

3) Using StringBuffer/StringBuilder

Probably the simplest approach is to use StringBuffer or StringBuilder of the required string length and append zeros until the desired length to left pad or right pad string as given below.

Output

Note: If you are using Java 1.4 or lower version, use the StringBuffer class instead of the StringBuilder class.

4) Java String pad with zero using Apache Commons library

If you are using the Apache Commons library, you can use the leftPad method of StringUtils class to left pad a string or the rightPad method to right pad a string.

This method left pad a string with specified paddingChar till the specified size.

This method right pad a string with specified paddingChar till specified size.

Output

This example is a part of the Java String tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.