Java – Left pad a string with spaces or zeros

Java programs to add left padding to a string in such a way that total string length should be a fixed predefined number. For example, if we have a string of length 10, and we want to increase it’s length to 15 – by adding left padding then use the example given this post.

1. How left padding is added

When you add left padding, you essentially add a character repeatedly until string length reaches to defined length.

For example –			//no padding		//left padding of 4 spaces		//left padding of 4 dots		//left padding of 4 zeros

Read More: Java remove leading whitespaces from String

2. Java left padding with spaces

To add left padding, most useful and easy way is to use StringUtils.leftPad() method.

2.1. Maven dependency


2.2. Method Syntax (overloaded)

 * @param str  		- the String to pad out, may be null
 * @param size 		- the size to pad to i.e. Total length of result string
 * @param padChar  	- the character or string to pad with
 * @return left padded String or original String if no padding is necessary or if null String input

public static String leftPad(final String str, final int size) {...}
public static String leftPad(final String str, final int size, String padStr) {...}
public static String leftPad(final String str, final int size, final char padChar) { ... }

2.3. Left padding example

System.out.println( StringUtils.leftPad("howtodoinjava", 20, " ") );
System.out.println( StringUtils.leftPad("howtodoinjava", 30, " ") );
System.out.println( StringUtils.leftPad("howtodoinjava", 15, " ") );

Program output:


3. Java left pad a string with zeros

Java program to use StringUtils.leftPad() method to left pad a string with zeros, by adding leading zeros to string.

System.out.println( StringUtils.leftPad("0123456789", 10, "0") );
System.out.println( StringUtils.leftPad("789", 10, "0") );
System.out.println( StringUtils.leftPad("56789", 10, "0") );

Program output:


4. Summary

In above examples, we learned to left pad string with spaces to fixed length. We also saw to left pad a number with zeros.

Use this left padding to format strings to fixed length – to display in UI.

Happy Learning !!


StringUtils Java Doc

Leave a Reply

Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.

Our Blogs

REST API Tutorial