To right pad a string in Java, we add spaces or another character at the end until the string has a fixed length. The shortest way is String.format(“%-10s”, text), where the minus sign keeps the text on the left so the spaces go on the right.
We use right padding to print aligned columns in console reports and to build fixed-width text records, for example a bank export file where every name field has 20 characters.
The following example pads “apple” and “42” with spaces, zeros and dots. The square brackets around some results only make the trailing spaces visible.
String spaces = "[" + String.format("%-10s", "apple") + "]"; // [apple ] (5 spaces added)
String leftZeros = String.format("%010d", 42); // 0000000042 (zeros go on the LEFT)
String commons = "[" + StringUtils.rightPad("apple", 10) + "]"; // [apple ]
String rightZeros = StringUtils.rightPad("42", 6, '0'); // 420000 (zeros on the right)
String dots = "apple" + ".".repeat(10 - "apple".length()); // apple..... (any character)
Notice that String.format() pads only with spaces, and its 0 flag puts zeros on the left of a number. So when we need zeros or any other character on the right, we use StringUtils.rightPad() or String.repeat().
Next, we compare right and left padding and pad with any character, first in plain Java and after that with Apache Commons Lang and Guava. We also cut strings that are longer than the width and print an aligned text table with printf.
1. Right Padding vs Left Padding
Padding means adding characters to a string until the string reaches a fixed length. We call the added characters pad characters, and the original text stays the same.
- Right padding adds the pad characters at the end, so the text stays on the left.
- Left padding adds the pad characters at the start, so the text moves to the right.
- Centering splits the pad characters between both sides.

We pad “kiwi” to 8 characters, and each table row shows the same padding done with the JDK and with Apache Commons Lang.
| Padding | String.format() | Result | Commons Lang | Result |
|---|---|---|---|---|
| Right | String.format(“%-8s”, “kiwi”) | “kiwi “ | StringUtils.rightPad(“kiwi”, 8, ‘.’) | “kiwi….” |
| Left | String.format(“%8s”, “kiwi”) | ” kiwi” | StringUtils.leftPad(“kiwi”, 8, ‘.’) | “….kiwi” |
| Center | no format flag | – | StringUtils.center(“kiwi”, 8, ‘.’) | “..kiwi..” |
In practice, we right pad text, such as names in a report column, and left pad numbers, such as an order number 000042.
2. Using Plain Java
The String class has no rightPad() method, but the JDK gives us three ways to right pad without a library.
2.1. String.format() With the Minus Flag
The format %-Ns prints a string in a field of N characters. The – flag aligns the text to the left, so the spaces go on the right. When we leave out the – flag, the spaces go on the left.
String banana = "[" + String.format("%-8s", "banana") + "]"; // [banana ]
String number = "[" + String.format("%-8s", 42) + "]"; // [42 ] (numbers work too)
String plum = "[" + "%-8s".formatted("plum") + "]"; // [plum ] (Java 15+)
int width = 12;
String wide = "[" + String.format("%-" + width + "s", "plum") + "]"; // [plum ]
String notCut = "[" + String.format("%-3s", "banana") + "]"; // [banana] (longer text is not cut)
When the width comes from a variable, we build the format string, for example “%-12s”, with string concatenation.
String.format() pads only with spaces, and the 0 flag pads numbers with zeros only on the left. When we combine the – and 0 flags, String.format() throws IllegalFormatFlagsException.
String bad = String.format("%-010d", 42);
// java.util.IllegalFormatFlagsException: Flags = '-0'
String zeros = String.format("%-6s", "42").replace(' ', '0'); // 420000
String wrong = String.format("%-12s", "green tea").replace(' ', '0'); // green0tea000 (wrong)
The replace() trick changes every space, including the spaces inside the text, so we use it only when the text has no spaces of its own.
2.2. Padding With Any Character Using repeat()
String.repeat(n) (Java 11+) returns the string repeated n times. We compute how many characters are missing and append that many pad characters, so any character works as the pad.
String fruit = "apple";
String dotted = fruit + ".".repeat(10 - fruit.length()); // apple.....
String zeroed = fruit + "0".repeat(10 - fruit.length()); // apple00000
String tooLong = "watermelon!" + ".".repeat(10 - "watermelon!".length());
// java.lang.IllegalArgumentException: count is negative: -1
String safe = fruit + ".".repeat(Math.max(0, 3 - fruit.length())); // apple (already long enough)
When the text is longer than the width, the count becomes negative and repeat() throws IllegalArgumentException. So we wrap the count in Math.max(0, …) whenever the text can be longer than the width.
2.3. A Custom rightPad() Method
When we want one reusable method, a small helper method handles null input and pad strings with more than one character. It returns a long string unchanged. The method repeats the pad string and then cuts the pad to the missing length with substring().
public static String rightPad(String input, int length, String padStr) {
if (input == null || padStr == null || padStr.isEmpty()) {
return input;
}
int padLength = length - input.length();
if (padLength <= 0) {
return input;
}
String pad = padStr.repeat(padLength).substring(0, padLength);
return input + pad;
}
We test the rightPad() helper with a multi-character pad and with null input.
String digits = rightPad("123456789", 10, "0"); // 1234567890
String spaced = rightPad("apple", 10, " "); // "apple "
String mixed = rightPad("apple", 10, "-="); // apple-=-=- (pad cut to fit)
String longer = rightPad("watermelon", 5, "."); // watermelon (no change)
String noText = rightPad(null, 10, "."); // null
The substring() call matters for a pad string such as “-=”. Without the cut, “-=”.repeat(5) adds 10 characters, so the result has 15 characters instead of 10.
3. Right Pad a String using StringUtils.rightPad()
The StringUtils class from Apache Commons Lang has ready-made padding methods. StringUtils.rightPad() returns null for a null input instead of throwing a NullPointerException, and it comes in three versions.
public static String rightPad(String str, int size); // pads with spaces
public static String rightPad(String str, int size, char padChar);
public static String rightPad(String str, int size, String padStr);
3.1. Maven
Add the latest version of Apache Commons Lang to the project.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.21.0</version>
</dependency>
3.2. Right Padding with Spaces
The rightPad(str, size) version pads with spaces. When the string is already long enough, rightPad() returns it unchanged and does not cut it.
String one = StringUtils.rightPad("java", 5); // "java "
String ten = StringUtils.rightPad("java", 10, " "); // "java "
String kept = StringUtils.rightPad("javascript", 4); // javascript (no change, no cut)
String noText = StringUtils.rightPad(null, 10); // null
String empty = StringUtils.rightPad("java", 8, ""); // "java " (empty padStr means spaces)
3.3. Right Padding with Zeros
For zeros, we pass ‘0’ as a char or “0” as a String. When the pad string has several characters, rightPad() repeats it and cuts it to fit, the same as our custom method.
String five = StringUtils.rightPad("123", 5, "0"); // 12300
String ten = StringUtils.rightPad("123", 10, '0'); // 1230000000
String mixed = StringUtils.rightPad("java", 10, "-="); // java-=-=-=
3.4. leftPad() and center()
StringUtils has matching methods for the other two directions. The method leftPad() adds the characters at the start, whereas center() puts half of them on each side and the extra one on the right.
String right = StringUtils.rightPad("apple", 10, '*'); // apple*****
String left = StringUtils.leftPad("apple", 10, '*'); // *****apple
String center = StringUtils.center("apple", 10, '*'); // **apple***
String orderNo = StringUtils.leftPad("42", 6, '0'); // 000042
String even = StringUtils.center("java", 10, '*'); // ***java***
String odd = StringUtils.center("java", 9, '*'); // **java***
String spaced = StringUtils.center("java", 10); // " java "
We use these methods when we left, right or center align a string, for example the shop name and the item lines on a printed receipt.
4. Right Pad a String using Strings.padEnd()
If the project already uses Guava, its Strings class has padding methods too. Add the latest version of Guava to the project.
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>33.7.2-jre</version>
</dependency>
Strings.padEnd() right pads with one char, and Strings.padStart() left pads.
String digits = Strings.padEnd("123456789", 10, '0'); // 1234567890
String site = Strings.padEnd("howtodoinjava", 20, ' '); // "howtodoinjava "
String kept = Strings.padEnd("javascript", 4, '.'); // javascript (no change)
String orderNo = Strings.padStart("42", 6, '0'); // 000042
String noText = Strings.padEnd(null, 10, '.'); // NullPointerException
String safe = Strings.padEnd(Strings.nullToEmpty(null), 10, '.'); // ..........
Unlike StringUtils, Guava throws a NullPointerException for a null string, and it accepts only a single char as the pad. So we wrap a string that can be null in Strings.nullToEmpty() first.
5. Truncating a String That Is Longer Than the Width
The padding methods we have seen never cut a long string, so in a fixed-width column a long name pushes the next column to the right. To get N characters every time, we pad short strings and cut long strings.
The format %-6.6s does both, because the first 6 is the minimum width and the precision .6 is the maximum number of characters.
String cut = String.format("%-6.6s", "watermelon"); // "waterm"
String padded = String.format("%-6.6s", "fig"); // "fig "
String commons = StringUtils.rightPad(StringUtils.truncate("watermelon", 6), 6); // "waterm"
String dots = StringUtils.abbreviate("watermelon", 6); // "wat..."
Without a library, we write a short helper method that uses substring() to cut and repeat() to pad.
public static String fitWidth(String text, int width) {
if (text.length() > width) {
return text.substring(0, width);
}
return text + " ".repeat(width - text.length());
}
String cut = fitWidth("watermelon", 6); // "waterm"
String padded = fitWidth("fig", 6); // "fig "
When the user should see that the text was cut, we use StringUtils.abbreviate(), which ends the result with “…”.
6. Formatting a Table With printf
We use right padding most often to print aligned columns in the console. System.out.printf() takes the same format as String.format() and prints the result, and %n adds a line break.
To print a stock list, we right pad the text column with %-10s and left pad the number column with %5d.
Map<String, Integer> stock = new LinkedHashMap<>();
stock.put("apple", 5);
stock.put("banana", 12);
stock.put("kiwi", 3);
System.out.printf("%-10s|%5s%n", "Fruit", "Qty");
System.out.println("-".repeat(16));
stock.forEach((name, qty) -> System.out.printf("%-10s|%5d%n", name, qty));
Every row lines up because each column always has the same width.
Fruit | Qty
----------------
apple | 5
banana | 12
kiwi | 3
We align text to the left because it reads better that way, whereas we align numbers to the right so their digits line up for comparison, which is the default for numbers in printf() when we leave out the – flag.
7. Right Padding FAQs
7.1. How Do I Right Pad a Number With Zeros?
We convert the number to a String first and then pad the string. Zeros on the right change the value (42 becomes 420000), so we use them only for fixed-width text fields, not for numbers we calculate with.
String commons = StringUtils.rightPad(String.valueOf(42), 6, '0'); // 420000
String plain = String.valueOf(42) + "0".repeat(4); // 420000
7.2. Why Does String.format(“%-010d”, 42) Throw an Exception?
Because the two flags conflict. The 0 flag pads a number with zeros on the left, whereas the – flag moves the number to the left side, so Formatter throws IllegalFormatFlagsException with the message Flags = ‘-0’.
To get zeros on the right, we use StringUtils.rightPad() or repeat() instead.
7.3. Which Method Should I Use?
The choice depends on the pad character and on whether a library is already in the project. Each row lists one way to right pad and its limits.
| Method | Pad character | null input | Longer text | Needs |
|---|---|---|---|---|
| String.format(“%-Ns”) | spaces only | prints “null” | kept (use %-N.Ns to cut) | JDK |
| s + c.repeat(n) | any string | NullPointerException | exception if n is negative | Java 11+ |
| StringUtils.rightPad() | any char or string | returns null | kept | Commons Lang |
| Strings.padEnd() | one char | NullPointerException | kept | Guava |
Without a library, we use String.format() for spaces and repeat() for other characters. When Commons Lang is already in the project, StringUtils.rightPad() is the shortest choice and also handles null.
8. Conclusion
In this Java String tutorial, we learned to right pad a string with spaces or any other pad character, such as zeros, so that the string has a fixed length.
String.format(“%-10s”) pads with spaces, and repeat() pads with any character. The Commons Lang methods StringUtils.rightPad() and leftPad() also handle null and multi-character pads, and center() splits the pad between both sides. When long text must be cut as well, we use %-N.Ns or a small helper method.
9. References
- Formatter JavaDoc (Java 25)
- String JavaDoc (Java 25)
- StringUtils JavaDoc (Commons Lang)
- Strings JavaDoc (Guava)
Happy Learning !!