Left Pad a String with Spaces or Zeros in Java (5 Ways)

Left pad a string in Java with spaces or leading zeros using String.format(), repeat(), StringUtils.leftPad() and Guava, with negative numbers and nulls.

The number 42 and the number -42 padded to 6 characters with d, showing the minus sign kept in front of the zeros

To left pad a string in Java, we add spaces or zeros before it until it reaches a fixed length, with String.format(“%8s”, text) for spaces, String.format(“%08d”, number) for numbers, or “0”.repeat(missing) + text for any string and any pad character. A string that is already long enough stays unchanged.

We left pad values for invoice and order numbers with leading zeros, file names that must sort in the right order, right-aligned console output and fixed-width records for banks and legacy systems.

The following example pads short values to a length of 8 in four ways.

String spaces = String.format("%8s", "42");              // "      42"
String zeros = String.format("%08d", 42);                // "00000042"
String code = "0".repeat(8 - "A7".length()) + "A7";      // "000000A7"
String dots = leftPad("Java", 8, '.');                   // "....Java"

Notice that the 0 flag of String.format() works only for numbers, so the text value A7 gets its zeros from repeat(), and leftPad() is the small helper from section 3. We also look at negative numbers, values longer than the target length, Apache Commons StringUtils and Guava.

1. Left Pad a Number with Zeros using String.format()

In the format syntax, %08d means “print an integer in at least 8 characters and fill the free space on the left with zeros”. The flag works for int, long, BigInteger and, with %f, for decimal numbers.

The number 42 and the number -42 padded to 6 characters with %06d, showing the minus sign kept in front of the zeros
Zero padding fills the free space on the left, and a minus sign stays in front of the zeros
String invoice = "INV-" + String.format("%05d", 42);        // "INV-00042"
String negative = String.format("%06d", -42);              // "-00042"
String longValue = String.format("%010d", 9876543210L);    // "9876543210"
String tooLong = String.format("%03d", 123456);            // "123456"
String price = String.format(java.util.Locale.ROOT, "%08.2f", 3.5);   // "00003.50"

We can see two rules in the output. The minus sign is printed first and the zeros come after it, and the width is a minimum, so a longer number is never cut. The decimal example passes Locale.ROOT, because String.format() uses the default locale and prints a comma as the decimal separator in many European locales.

Zero padding solves a common sorting problem. A shop that names invoice files invoice-9.pdf and invoice-10.pdf sees the tenth file listed before the ninth in a folder sorted by name, whereas invoice-00009.pdf and invoice-00010.pdf sort in the order they were created.

2. Left Pad a String with Spaces using String.format()

For spaces, the specifier %Ns right aligns any string in a field of N characters. The width can come from a variable when we build the pattern at runtime.

int length = 10;
String padded = String.format("%" + length + "s", "Java");   // "      Java"
String same = "%10s".formatted("Java");                        // "      Java"
String zeroText = String.format("%05s", "Java");               // FormatFlagsConversionMismatchException

The 0 flag is not allowed with %s, so %05s throws FormatFlagsConversionMismatchException instead of padding the text with zeros. A trick seen on many sites pads with spaces and replaces them with zeros, but it also replaces the spaces inside the value.

String broken = String.format("%6s", "A 7").replace(' ', '0');   // "000A07"

The value A 7 has turned into A07, so the replace trick is only safe for values that never contain a space. The string alignment tutorial covers right, left and center alignment with the same specifiers.

3. Left Pad a String using Plain Java

Since Java 11, String.repeat() builds the padding in one call, so a helper method needs no loop and no library. We compute how many characters are missing and put that many pad characters in front of the input.

static String leftPad(String input, int length, char padChar) {
    Objects.requireNonNull(input, "input");
    int missing = length - input.length();
    return missing <= 0 ? input : String.valueOf(padChar).repeat(missing) + input;
}
String account = leftPad("12345", 10, '0');      // "0000012345"
String label = leftPad("Java", 8, ' ');          // "    Java"
String unchanged = leftPad("Javascript", 4, '.'); // "Javascript"
String missing = leftPad(null, 5, '0');          // NullPointerException: input

The missing <= 0 check returns a long input unchanged, because repeat() throws IllegalArgumentException for a negative count. For null, the helper fails with a clear message instead of returning null, so a missing account number shows up at the call site and not in a file sent to a bank.

When the padding is a string of several characters, we repeat it often enough and cut the result to the missing length.

static String leftPad(String input, int length, String padStr) {
    int missing = length - input.length();
    if (missing <= 0 || padStr.isEmpty()) {
        return input;
    }
    return padStr.repeat(missing / padStr.length() + 1).substring(0, missing) + input;
}
String pattern = leftPad("7", 5, "ab");          // "abab7"

4. Left Pad a String with StringUtils.leftPad()

Apache Commons Lang has StringUtils.leftPad() with overloads for a pad character and a pad string. It is a good choice in projects that already depend on commons-lang3, whose current version is 3.21.0. To right pad, the same class has rightPad(), and our right pad a string tutorial shows it with examples.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.21.0</version>
</dependency>

The three overloads take the input string, the total length of the result and an optional pad character or pad string. Without the third argument, the method pads with spaces.

String withSpaces = StringUtils.leftPad("Java", 8);           // "    Java"
String withZeros = StringUtils.leftPad("789", 10, '0');        // "0000000789"
String withString = StringUtils.leftPad("7", 5, "ab");         // "abab7"
String nullInput = StringUtils.leftPad(null, 5, '0');          // null
String emptyPad = StringUtils.leftPad("Java", 8, "");          // "    Java"

Unlike our helper, leftPad() returns null for a null input, and it falls back to a space when the pad string is empty or null.

5. Left Pad a String using Strings.padStart()

Google Guava offers Strings.padStart(), which takes a single pad character. Guava 33.7.2-jre is the current release, and the method rejects a null input with NullPointerException.

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>33.7.2-jre</version>
</dependency>
String guavaZeros = Strings.padStart("123456789", 10, '0');   // "0123456789"
String guavaDots = Strings.padStart("Java", 8, '.');           // "....Java"
String guavaNull = Strings.padStart(null, 5, '0');             // NullPointerException

The table compares the options. For new code, the JDK methods from the first three sections cover every case, so we add a library only when the project already uses it.

MethodPads withNull inputNeeds a library
String.format(“%08d”, n)Zeros, numbers only” null” for a null IntegerNo
String.format(“%8s”, s)Spaces” null”No
“0”.repeat(n) + sAny character or stringNullPointerException in our helperNo, Java 11+
StringUtils.leftPad()Any character or stringReturns nullCommons Lang
Strings.padStart()One characterNullPointerExceptionGuava

6. Building a Fixed-Width Record

Banks, payroll providers and mainframe systems still exchange files where every field has a fixed position. A payment record can require a 10-digit account number padded with zeros, an amount in cents padded to 12 digits, and a name padded with spaces to 20 characters on the right.

String account = leftPad("12345", 10, '0');                   // "0000012345"
String cents = String.format("%012d", 4_999L);                // "000000004999"
String name = String.format("%-20.20s", "Lokesh Gupta");      // "Lokesh Gupta        "
String record = account + cents + name;
int recordLength = record.length();                           // 42

The precision in %-20.20s cuts a longer name to 20 characters, which keeps every following field in its position. Left padding never cuts a value, so we validate the length of account numbers before building the record.

7. Left Padding FAQs

Leading zeros raise more questions than spaces do, mostly about text values and about the way back.

7.1. What does %05d mean in Java?

The specifier %05d prints an integer in at least 5 characters, padding with zeros on the left. The 0 is the zero-padding flag, 5 is the minimum width and d is the decimal integer conversion, so 42 becomes 00042.

7.2. How do I add leading zeros to a string that is not a number?

We use repeat(), because %05s throws FormatFlagsConversionMismatchException.

String sku = "0".repeat(Math.max(0, 6 - "B12".length())) + "B12";   // "000B12"

7.3. What happens if the string is longer than the length?

The input comes back unchanged from String.format(), repeat(), StringUtils.leftPad() and Strings.padStart(). None of them cuts the value, so a field can become longer than planned. To cut, we add a precision such as %-10.10s or call substring().

7.4. How do I remove leading zeros from a string?

For a number, we parse it with Integer.parseInt(). For a text value, a regular expression removes the zeros and keeps a single 0 when the value is all zeros.

String trimmed = "007".replaceFirst("^0+(?!$)", "");     // "7"
String zero = "000".replaceFirst("^0+(?!$)", "");        // "0"

8. Conclusion

For numbers, String.format(“%0Nd”, value) adds leading zeros and keeps the minus sign in front. For spaces, %Ns does the job, and for text with zeros or any other character, repeat() builds the padding in one line.

A small leftPad() helper with a null check and a length check is all most projects need, while StringUtils.leftPad() and Guava’s Strings.padStart() fit projects that already depend on those libraries. The Java String tutorial links the related String tasks.

9. References

Happy Learning !!

Source Code on Github

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.