How to format a Java string with leading zero?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Use String.format("%05d", value) to pad an integer with leading zeros to a fixed width. The 0 flag tells the formatter to pad with zeros instead of spaces, and the number after it specifies the total width. For example, String.format("%05d", 42) produces "00042".
This is the standard approach in Java for invoice numbers, time components, file naming, and any situation where a fixed-width numeric string is required. The rest of this article covers the format specifier syntax in detail, alternative approaches with DecimalFormat and StringUtils, handling edge cases with negative numbers, and how to pad strings (not just integers) with leading characters.
The String.format Approach
Format Specifier Breakdown
The format specifier %05d consists of four parts:
| Part | Meaning |
% | Starts the format specifier |
0 | Use zero-padding instead of space-padding |
5 | Minimum total width of the output |
d | Format as a decimal integer |
The width value controls how many characters the result will be at minimum. If the number already has that many or more digits, no padding is added:
The formatter never truncates. If the value is wider than the specified width, the full value is printed.
Dynamic Width
When the width needs to be configurable, build the format string dynamically:
This helper method is worth creating when padding appears in multiple places across the codebase. It centralizes the format string and makes width changes trivial.
Formatting long Values
The same specifier works with long values:
Use d for both int and long. Java's formatter handles the promotion automatically.
Using DecimalFormat
DecimalFormat provides pattern-based numeric formatting and is part of java.text:
Each 0 in the pattern represents a required digit position. If the number has fewer digits, zeros fill the remaining positions from the left.
When to Use DecimalFormat Over String.format
| Scenario | Better choice |
| Simple fixed-width integer padding | String.format |
| Locale-aware formatting (grouping separators, decimal points) | DecimalFormat |
Pattern includes decimal places (e.g., "000.00") | DecimalFormat |
| Format string is loaded from configuration | DecimalFormat |
| Part of a larger formatted message with multiple placeholders | String.format |
Using printf for Console Output
When the padded value is only needed for printing, System.out.printf uses the same format syntax as String.format:
The %n at the end produces a platform-appropriate newline. This is convenient for logging and debugging but does not produce a String you can pass to other methods. If you need the string value elsewhere, use String.format.
Padding Strings (Not Just Numbers)
The %0Nd specifier only works with numeric types. If you need to pad a string with leading zeros (or any other character), Java does not have a single built-in method, but there are several clean approaches.
Using String.format with Right-Alignment and Replace
This right-aligns the string in a 10-character field (padded with spaces), then replaces spaces with zeros. It works but fails if the original string contains spaces.
Using Apache Commons StringUtils.leftPad
This is the cleanest option when Apache Commons is already a dependency. It handles all edge cases and supports any padding character.
Using String.repeat (Java 11+)
This is dependency-free and readable. The Math.max(0, ...) guard prevents negative repeat counts when the input is already wider than the target.
Handling Negative Numbers
Negative values include the minus sign as part of the formatted width:
The sign character counts toward the total width. A width of 6 with a negative value leaves 5 positions for digits. This is usually the correct behavior for financial or accounting displays, but you should be aware of it when defining the width.
If you need the sign to appear after the zeros (unusual but sometimes required), you must handle it manually:
Practical Use Cases
File Naming with Sequential Numbers
Zero-padded filenames sort correctly in file explorers and command-line listings because 0002 sorts before 0010 lexicographically.
Time Display
Invoice and Reference Numbers
Common Pitfalls
Expecting an int to preserve leading zeros. Java integers are numeric values, not strings. int x = 00042 is just 42. Leading zeros in integer literals actually indicate octal notation (042 = 34 in decimal). Always format at the display boundary.
Formatting early and parsing back. Converting a padded string back to an integer strips the zeros:
Keep the padded value as a String once formatted. Do not round-trip through parseInt if you need the zeros.
Hardcoding format strings across the codebase. Scattering "%05d" in 20 different files means changing the width requires 20 edits. Extract it into a constant or utility method.
Confusing DecimalFormat pattern characters. In DecimalFormat, 0 means "required digit" and # means "optional digit." Using "#####" instead of "00000" will not add leading zeros because # suppresses them.
Using %0Ns instead of %0Nd. The zero-pad flag only works with numeric conversions (d, o, x). Using it with s (string) throws FormatFlagsConversionMismatchException.
Summary
String.format("%05d", value)is the standard way to add leading zeros to integers in Java.- The
0flag enables zero-padding; the number after it sets the minimum width. DecimalFormatis better for locale-aware or pattern-based numeric formatting.- For string padding, use
StringUtils.leftPad,String.repeat(Java 11+), or theformat-and-replacetrick. - Negative numbers include the sign in the width count.
- Leading zeros are a display concern. Keep values as numbers for computation and format to strings only at the output boundary.
- Never use
%0Ns(zero-pad with string conversion). Zero-padding is only valid with numeric format specifiers.

