Java String Formatting - How to apply zero padding in integers using String#printf()?

Java String Formatting Java 

This example shows how to append zeros before an integer with String#printf()

Syntax: %0nd where n is any positive integer

package com.logicbig.example.string;

import java.util.IllegalFormatFlagsException;

public class StringPrintfIntegerZeroPadding {

public static void main(String[] args) {
//padding with zeros
System.out.printf("[%04d]%n", 9);

//right padding with zeros is not possible
try {
System.out.printf("[%-04d]%n", 9);
} catch (IllegalFormatFlagsException e) {


java.util.IllegalFormatFlagsException: Flags = '-0'

See Also