Java String Handling

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. Example also shows how to left pad string with zero, right pad string with zero using various ways.

How to pad string with zero in Java?

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

1) Java String pad with zero using substring method

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

Output

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 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 pad 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) Java String pad with zero 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 string with zeros. 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

Above example uses 10 as desired length and zero 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) Java String pad with zero using StringBuffer/StringBuilder

Probably the simplest approach is to use StringBuffer/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 StringBuffer instead of StringBuilder class.

4) Java String pad with zero using Apache Commons library

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

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

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

Output

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

 

Join 1000+ fellow learners! Enter your email address below: