Question

How to Left Pad Integers with Leading Zeros in Java

javaformattingzero-pad

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:

  • 1 becomes "0001"
  • 25 becomes "0025"
  • 300 becomes "0300"
  • 9999 stays "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:

  • String.format() for simple formatting
  • Formatter for reusable formatted output
  • DecimalFormat for number formatting patterns

For most beginners, String.format("%04d", number) is the easiest and clearest solution.

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.

  • 1 takes one slot, so three zeros are added: 0001
  • 25 takes two slots, so two zeros are added: 0025
  • 300 takes 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.

Take Quiz

Syntax and Examples

The most common syntax in Java is:

String result = String.format("%04d", number);

What %04d means

  • % starts a format specifier
  • 0 means pad with zeros instead of spaces
  • 4 means the total width should be 4 characters
  • d means 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

System.out.println(String.format("%04d", 1));    // 0001
System.out.println(String.format("%04d", 25));   // 0025
System.out.println(String.format("%04d", 300));  // 0300
System.out.println(String.format("%04d", 9999)); // 9999

Using DecimalFormat

Another option is DecimalFormat:

import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        DecimalFormat df = new DecimalFormat("0000");

        System.out.println(df.format(1));    // 0001
        System.out.println(df.format(25));   // 0025
        System.out.println(df.format(300));  // 0300
        System.out.println(df.format(9999)); // 9999
    }
}

This is also useful, especially when you want a reusable formatting object.

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:

  1. int number = 25;

    • A variable named number is created.
    • It stores the integer value 25.
  2. String result = String.format("%04d", number);

    • Java reads the format pattern %04d.
    • d tells Java the value is an integer.
    • 4 tells Java the result must be 4 characters wide.
    • 0 tells Java to fill extra space with zeros.
    • Since 25 only has 2 digits, Java adds 2 zeros on the left.
    • The final string becomes "0025".
  3. System.out.println(result);

    • The formatted string is printed.
    • Output: 0025

Another trace

System.out.println(String.format("%04d", 7));
  • 7 has 1 digit
  • Width required is 4
  • Java adds 3 zeros
  • Result: 0007

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.

Take Quiz

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) {
    if (number < 0 || number > 9999) {
        throw new IllegalArgumentException("Number must be between 0 and 9999");
    }
    return String.format("%04d", number);
}

Configuration-driven formatting

In larger systems, width may come from config instead of being hardcoded.

Error handling

Formatting itself is simple, but developers still make sure invalid input, null values, or out-of-range numbers are handled earlier in the application flow.

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

System.out.println(String.format("%04d", 12345));
// 12345

The width is a minimum, not a maximum. Java will not trim the number.

4. Confusing spaces with zeros

Broken example:

String result = String.format("%4d", 12);

This pads with spaces, not zeros.

Correct version:

String result = String.format("%04d", 12);

5. Writing manual padding when built-in formatting already exists

You could write custom logic, but it is usually harder to read and maintain.

Less ideal:

String s = Integer.toString(5);
while (s.length() < 4) {
    s = "0" + s;
}

Better:

String s = String.format("%04d", 5);

6. Not thinking about negative numbers

System.out.println(String.format("%04d", -5));

The minus sign is part of the formatted result, so the output may not look like simple zero-padding for positive numbers. If your logic only expects positive values, validate that explicitly.

Comparisons

ApproachExampleBest forNotes
String.formatString.format("%04d", 5)Simple one-off formattingMost beginner-friendly
DecimalFormatnew DecimalFormat("0000").format(5)Repeated numeric formattingGood when using formatting patterns
Manual paddingloop or string concatenationLearning exercise onlyUsually less clear and more error-prone

String.format vs DecimalFormat

FeatureString.formatDecimalFormat
Easy for beginnersYesYes
Good for one valueYesYes
Reusable formatter objectNoYes
Uses printf-style syntaxYesNo
Focused on number formatting patternsNoYes

%4d vs %04d

FormatOutput for 12Meaning
%4d 12Pad with spaces
%04d0012Pad with zeros
Take Quiz

Cheat Sheet

String.format("%04d", number)

Meaning of %04d

  • % = start format
  • 0 = pad with zeros
  • 4 = minimum width is 4
  • d = 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 = new DecimalFormat("0000");
df.format(7); // 0007

Important rules

  • The result is a String
  • Width is a minimum, not a maximum
  • %4d uses spaces
  • %04d uses zeros
  • Use %d for integers
  • Validate input if only certain ranges are allowed

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, DecimalFormat is also a good choice.

Can I pad negative numbers with zeros?

Yes, but the minus sign affects the output. If your use case only expects positive values, validate the input first.

Take Quiz

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 main method.
  • 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.
Take Quiz

Keep learning

Related questions

View more