Close

Java String Formatting - How to add padding using String#printf()?

Java String Formatting Java 

This example shows how to do padding (i.e align text by adding spaces) with String#printf()

The format specifiers having pattern %N or %-N is used for this purpose, where N is an integer.

%N is for left padding and %-N is for right padding.

package com.logicbig.example.string;

public class StringPrintfPadding {

public static void main(String[] args) {
//left padding
System.out.printf("Result: %20s%n", "test");
//right padding
System.out.printf("Result: %-20s%n", "test");
System.out.printf("%-20s result%n", "test");
//formatting multiple lines in columns
for (int i = 7; i < 300; i += 50) {
System.out.printf("[Product:%4s %-4d %10f]%n", i, i * 10, i / 2f);
}
}
}

Output

Result:                 test
Result: test
test result
[Product: 7 70 3.500000]
[Product: 57 570 28.500000]
[Product: 107 1070 53.500000]
[Product: 157 1570 78.500000]
[Product: 207 2070 103.500000]
[Product: 257 2570 128.500000]




See Also