Close

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

Java String Formatting Java 

This example shows how to apply padding in integers with String#printf()

Syntax: %nd where n is any positive or negative integer

package com.logicbig.example.string;


public class StringPrintfIntegerPadding {

public static void main(String[] args) {
//padding without zeros
System.out.printf("[%4d]%n", 9);
//padding with zeros
System.out.printf("[%04d]%n", 9);
//right padding
System.out.printf("[%-4d]%n", 3);
System.out.printf("[%-10d %d]%n", 6, 3);

}
}

Output

[   9]
[0009]
[3 ]
[6 3]




See Also