Question
How can you add leading zeros to an integer when converting it to a String in Java?
For example, if you want numbers up to 9999 to always be shown with four digits, the output should look like this:
1 -> "0001"
25 -> "0025"
300 -> "0300"
9999 -> "9999"
What is the correct way to format an integer in Java so it is left-padded with zeros?
Short Answer
By the end of this page, you will understand how to format integers as fixed-width strings in Java by adding zeros on the left. You will learn the most common solutions, when to use each one, and how to avoid mistakes when formatting numbers for IDs, file names, and display output.
Concept
In Java, numbers and strings are different types of data. An int stores a numeric value, while a String stores text. If you want a number like 1 to appear as "0001", you are no longer dealing with the raw number itself—you are formatting it for display.
Left-padding with zeros means making the output a fixed width by adding 0 characters before the number until it reaches the required length.
For example, if the width is 4:
1becomes"0001"25becomes"0025"300becomes"0300"9999stays"9999"
This matters in real programs because consistent formatting is often required for:
- invoice numbers
- report IDs
- timestamps
- file names like
image0001.png - user-facing labels
In Java, the most common ways to do this are:
Mental Model
Think of the formatted output as a 4-slot display board.
If your number does not fill all 4 slots, Java fills the empty slots on the left with zeros.
1takes one slot, so three zeros are added:000125takes two slots, so two zeros are added:0025300takes three slots, so one zero is added:0300
It is like placing a short word into a fixed-size label. If the label must always have the same width, extra characters are added to make it fit.
Syntax and Examples
The most common syntax in Java is:
String result = String.format("%04d", number);
What %04d means
%starts a format specifier0means pad with zeros instead of spaces4means the total width should be 4 charactersdmeans format the value as a decimal integer
Example using String.format
public class Main {
public static void main(String[] args) {
int number = 1;
String result = String.format("%04d", number);
System.out.println(result); // 0001
}
}
More examples
Step by Step Execution
Consider this code:
int number = 25;
String result = String.format("%04d", number);
System.out.println(result);
Here is what happens step by step:
-
int number = 25;- A variable named
numberis created. - It stores the integer value
25.
- A variable named
-
String result = String.format("%04d", number);- Java reads the format pattern
%04d. dtells Java the value is an integer.4tells Java the result must be 4 characters wide.0tells Java to fill extra space with zeros.- Since
25only has 2 digits, Java adds 2 zeros on the left. - The final string becomes
"0025".
- Java reads the format pattern
-
System.out.println(result);
Real World Use Cases
Leading-zero formatting is common in many real applications.
File naming
String fileName = "image_" + String.format("%04d", 7) + ".png";
// image_0007.png
This helps files sort correctly in alphabetical order.
Invoice or order numbers
String orderId = "ORD-" + String.format("%06d", 125);
// ORD-000125
Ticket or queue systems
String token = String.format("%03d", 9);
// 009
Report generation
When exporting rows or naming generated reports, fixed-width numbers keep output consistent.
User interface display
A dashboard might display item numbers, employee codes, or batch IDs with a standard width for readability.
Real Codebase Usage
In real projects, developers often use leading-zero formatting in small, reusable ways rather than writing custom padding logic every time.
Common pattern: helper method
public static String padToFourDigits(int number) {
return String.format("%04d", number);
}
This keeps formatting rules in one place.
Common pattern: dynamic width
public static String padWithZeros(int number, int width) {
return String.format("%0" + width + "d", number);
}
Example:
System.out.println(padWithZeros(42, 6)); // 000042
Validation before formatting
If a value must stay within a range, developers often validate first:
public static String formatCode(int number) {
(number < || number > ) {
();
}
String.format(, number);
}
Common Mistakes
1. Forgetting that the result is a String
Padding with zeros changes how the number looks, not its numeric value.
int number = 1;
String formatted = String.format("%04d", number);
formatted is a String, not an int.
2. Using the wrong format specifier
Broken example:
String result = String.format("%04s", 12);
%s is for strings, not integers. Use %d for decimal integers.
Correct version:
String result = String.format("%04d", 12);
3. Expecting numbers longer than the width to be cut off
Comparisons
| Approach | Example | Best for | Notes |
|---|---|---|---|
String.format | String.format("%04d", 5) | Simple one-off formatting | Most beginner-friendly |
DecimalFormat | new DecimalFormat("0000").format(5) | Repeated numeric formatting | Good when using formatting patterns |
| Manual padding | loop or string concatenation | Learning exercise only | Usually less clear and more error-prone |
String.format vs DecimalFormat
| Feature |
|---|
Cheat Sheet
String.format("%04d", number)
Meaning of %04d
%= start format0= pad with zeros4= minimum width is 4d= decimal integer
Common examples
String.format("%04d", 1); // 0001
String.format("%04d", 25); // 0025
String.format("%04d", 300); // 0300
String.format("%04d", 9999); // 9999
Dynamic width
String.format("%0" + width + "d", number);
Alternative with DecimalFormat
DecimalFormat df ();
df.format();
FAQ
How do I pad an integer with leading zeros in Java?
Use String.format("%04d", number) to format the integer as a 4-digit string with leading zeros.
What does %04d mean in Java?
It means: format as an integer (d), make the width 4, and pad missing characters with 0.
How do I make the width 6 instead of 4?
Change the format string:
String.format("%06d", number)
Does String.format return a number?
No. It returns a String.
What happens if the number has more digits than the width?
It is not cut off. Java prints the full number.
For example:
String.format("%04d", 12345) // "12345"
Should I use String.format or DecimalFormat?
For simple cases, String.format is usually easiest. If you are formatting many numbers with reusable patterns, is also a good choice.
Mini Project
Description
Build a small Java program that generates formatted product codes for an inventory system. Each product number should always appear as four digits, such as 0001, 0042, or 1200. This demonstrates how leading-zero formatting is used in real applications to create consistent, readable identifiers.
Goal
Create a program that formats several integer product numbers as 4-digit strings with leading zeros.
Requirements
- Create a Java class with a
mainmethod. - Store several integer values in an array.
- Format each number as a 4-digit string with leading zeros.
- Print each original number and its formatted version.
- Include at least one example where no extra zeros are needed.
Keep learning
Related questions
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Choosing a @NotNull Annotation in Java: Validation vs Static Analysis
Learn how Java @NotNull annotations differ, when to use each one, and how to choose between validation, IDE hints, and static analysis tools.
Convert a Java Stack Trace to a String
Learn how to convert a Java exception stack trace to a string using StringWriter and PrintWriter, with examples and common mistakes.