In programming, sometimes one deals with a situation where a string should be set to a fixed length. The length of a string can be altered by implementing padding methods. The string class in Java has no built-in method to imply padding. There are various methods, like formatting strings, to imply methods in Java programming.
This article discusses different ways to pad a string with zeros or spaces in Java programming and explains them with examples.
How to Pad a String With Zeros or Spaces in Java?
Augmenting characters like spaces or zeroes to either side of the string is called padding. In Java programming, padding can be done through different methods like format() or using functionalities like rightpad() or leftpad() by integrating libraries like the Spring Framework, Apache Commons, or Google Guava.
This article discusses different methods through which padding can be added to a string.
Custom Methods for Padding Strings
Java programming does not provide any built-in functions to add padding to a string. Therefore, we have to create our own methods to add padding to a string. Let us discuss different custom methods to add padding to a string.
Method 1: Using StringBuilder
Using the StringBuilder class, a string can be padded with zeros and spaces in Java programming. A StringBuilder class is used when alterations are to be made to a string without the need to create an object.
Code
The code below explains how padding can be done to a string using StringBuilder:
public static String paddingLeft(String inp_Str, int len) {
if (inp_Str.length() >= len) {
return inp_str;
}
StringBuilder sbuild = new StringBuilder();
while (sbuild.length() < len - inp_Str.length()) {
sbuild.append(' ');
}
sbuild.append(inp_Str);
return sbuild.toString();
}
}
In the above code,
- A public static string paddingLeft is defined, which takes two parameters: the input string defined as inp_str and the desired length “len” of the string after the padding has been done.
- If the length of the input string is greater than the required length, there is no need for padding, and the input is returned as it is.
- A string builder object sbuild is initialized and returns the padded string if the input string is lesser than the required length.
- The while loop calculates the number of characters that are required to get the desired length. It does so by subtracting the desired length from the input string’s length.
- The required number of spaces is appended to the string builder object and later to the input string.
- The padded string builder object “sb” utilizes the tostring() method. The code finally returns the padded string.
Test Case
public static void main(String[] args) {
String inp = "574";
System.out.println("The string before padding:" + inp);
int len = 8;
String res = paddingLeft(inp, len);
System.out.println("The string after padding:" + res);
}
In the above test case,
- An input string inp is defined with the value “576”. The string is displayed before any padding is done.
- An integer length is defined with the value 8.
- The parameters inp and len will be given to the function paddingLeft which will return the padded string. res stores the returned data.
- The string after the padding gets printed using the println() method.
Output
The following output shows that 5 characters (in this case, spaces) have been added to the input string of length 3 to get the desired length of 8:

Appending 0/Any Other Character
Any character can be appended to a string. In our case, we will append 0 to the left side of the string. This can be done by changing the character value in sb.append(‘ ’). Using sb.append(‘0’) will pad 0s to the string. The output of the resulting string with 0s padded is as follows:

Method 2: Using String.format
Java 5 provides a functionality called String.format creates a custom function to add padding to a string. String.format returns the formatted string by taking certain arguments. Padding in a string can be done through the String.format functionality in Java.
Code
The following code explains how padding can be added to a string using String.format:
public static String paddingLeft(String inp_str, int len) {
return String.format("%1$" + len + "s", inp_str)
}
In the above code,
- A public static string paddingLeft is defined which takes two parameters inp_str which is the input string to which the padding will be applied and len which is the desired length.
- The function returns the padded string. “%1$” states that the formatting will be done in the first argument. In this case, it will be the input string(inp_str). s represents that the argument will be taken as a string.
- The padded string will be returned.
Test Case
public static void main(String[] args) {
String inp = "5369";
System.out.println("The string before padding:" + inp);
int len = 10;
String res = paddingLeft(inp, len);
System.out.println("The string after padding:" + res);
}
In the above test case,
- An input string inp is given a value of “5369”. The string before the padding is printed.
- The desired length len is given the value of 10.
- The parameters will then be provided to the function paddingLeft which will return the padded string and store it in the string res.
- The padded string will be then printed.
Output
The following output shows that 6 characters (in this case, spaces) have been added to the input string of length 4 to get the desired length of 10:

Appending 0/Any Other Character
It is to be noted that using the default case, the padding will append the spaces in the input string. In order to append 0 or any other character in the input string, the replace() functionality is used. In order to get the right padding, a distinct flag %1$- is used. To append 0, replace(‘ ‘, ‘0’) will be integrated into the above function. The output after padding the string with 0 will be:

Method 3: Using substring()
Padding can be implemented in a string using the substring method in Java. The substring() method in Java gets the chunk of the main string.
public static String paddingLeft(String inp_str, int len) {
StringBuilder sbuild = new StringBuilder();
for (int i = 0; i < len; i++) {
sbuild.append(' ');
}
return sbuild.substring(inp_str.length()) + inp_str;
}
In the above code,
- A public static string paddingLeft is defined that takes the argument inp_str which is the input string and len which defines the required length of the padded string.
- A string builder object sbuild is created that executes a for loop that will keep on appending a space ‘ ’ using append() function until it reaches the required length.
- The code returns the padded string by applying the substring() method on sbuild and adding it before inp_str.
Test Case
public static void main(String[] args) {
String inp = "603";
System.out.println("The string before padding:" + inp);
int len = 5;
String res = paddingLeft(inp, len);
System.out.println("The string after padding:" + res);
}
In the above test case,
- An input string inp is defined with the value “603” and it is printed.
- An integer len is defined with the value 5 which will be the required length of the padded string.
- The parameters inp and len are given to the function paddingLeft and the result will be stored in the string res.
- The resultant padded value “603” with two spaces at the starting will be printed.
Output:
The output showing the padded string using the substring() method is as follows:

Appending 0/Any Other Character
If 0 or any other character is to be appended, the specific character will be provided to the append() method. To append 0s at the start of the string, 0 will be given to the append() function. The resulting output is by changing the sbuild.append(‘ ’) function to sbuild.append(‘0’) is:

Apache Commons Lang
External libraries in Java provide methods that can imply padding in the string. Apache Commons library contains functionalities that can be reused. It also contains classes like StringUtils that provide methods like rightpad(), leftpad(), and more to add padding to a string.
Importing the Library
To use the Apache Common library, it will be first integrated into the pom.xml file inside the dependencies tag.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
Example
The following code explains how padding can be done in a string using the leftPad method from stringUtils class:
import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
String inp = "5937";
System.out.println("The string before the padding:" + inp);
int len = 8;
char padChar = ' ';
String res = StringUtils.leftPad(inp, len, padChar);
System.out.println("The string after the padding:" + res);
}
}
In the above code,
- Inside the main class, an input string inp is defined with the value “5937”. The input string is printed using println().
- An integer len with a value of 8 is defined. This will be the length of the padded string.
- A character padchar ‘ ’ is defined, which will simply be a space added to the input string.
- The parameters inp, len, padchar are given to the function StringUtils.leftPad() which will return the padded string and store it in the result res.
- The padded string will be printed using System.out.println(“The string after the padding:” + res).
Output
In our code, the input string is “5937” having a length of 4. The required length is 8. Therefore, 4 spaces will be added before the string. The output displays padding done in a string using the leftPad() method of the StringUtils class provided by the Apache Commons library:

Appending 0/Any Other Character
To append 0 or any other character, the third argument will be modified, which in our case is padChar. The value of padChar will be set to 0. The resulting output with 4 0s padded at the starting will be:

Google Guava
The Guava library was designed by Google engineers and contains various functionalities, like collections, string manipulations, and more. It helps to remove redundant code. Using this library, padding can be applied to a string.
Importing the Library
To use the Google Guava library and its functionalities, first, add the following dependency in the dependencies tag in the pom.xml file.
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>31.0.1-jre</version>
</dependency>
Example
The following code explains how padding can be done in a string using the padStart method from the Strings class in the Guava library:
import com.google.common.base.Strings;
public class Main {
public static void main(String[] args) {
String inp = "2704";
System.out.println("The string before the padding:" + inp);
int len = 8;
char padChar = ' ';
String res = Strings.padStart(inp, len, padChar);
System.out.println("The string after the padding:" + res);
}
}
In the above code,
- The Strings class is imported from the Guava library.
- Inside the main class, an input string inp is defined with the value “270”. The input string is printed.
- A variable “len” with a value of 8 is defined.
- A varia
- ble named padchar ‘ ’ is defined, which will simply be a space added to the input string.
- The parameters inp, len, and padchar are given to the function Strings.padstart() that will return the padded string and store it in the result “res”.
- The padded string will be printed using System.out.println(“The string after the padding:” + res).
Output
In our code, the input string is “2704” with the length 4. The required length is 8. Therefore, 4 spaces will be added before the string. The output displays padding is done in a string using the leftPad() method of the StringUtils class provided by the Google Guava library:

Appending 0/Any Other Character
To append 0 or any other character, the third argument will be modified, which in our case is padChar. The value of padChar will be set to 0. Our input string is “2704” with a required length of 8. The resulting output “00002704” will be displayed:

Conclusion
A string is padded with zeros or spaces by using methods like leftPad or padStart using classes from external libraries like Apache Commons or Guava library. The classes containing these methods are first imported. There is no inherent method in Java programming to perform the padding in a string. Customs methods using string.format, substring, or StringBuilder are used to add padding to a string. This article discussed how to pad a string with zeros or spaces in Java programming and explained each method with an example.