String formatting
Build readable text with printf-style patterns instead of long chains of plus signs.
Open this lesson in the learning hubKey points
String.format,System.out.printfand"...".formatted(...)all share one pattern language.- Specifiers:
%stext,%dinteger,%fdecimal,%nnewline,%%percent. - Width and precision align output:
%-10spads right,%5dpads left,%.2fkeeps two decimals. %,dgroups thousands using the locale, so pass an explicitLocalewhenever another program reads the output.- Specifiers must match the arguments in type and count, or you get an
IllegalFormatExceptionat runtime. - With no alignment or precision to worry about, plain concatenation is clearer. Reach for format when the shape matters.
Example
import java.util.Locale;
public class Main {
public static void main(String[] args) {
System.out.printf("%s is %d years old%n", "Ada", 36);
System.out.println(String.format("pi to 2dp: %.2f", Math.PI));
System.out.println("formatted(): %s scored %d%%".formatted("Ada", 91));
System.out.println(String.format("|%-10s|%5d|", "left", 42));
System.out.println(String.format("|%10s|%-5d|", "right", 42));
System.out.println(String.format("zero padded id: %05d", 42));
System.out.println(String.format(Locale.US, "money: %,.2f", 1234567.891));
System.out.println(String.format(Locale.GERMANY, "same value, de-DE: %,.2f", 1234567.891));
System.out.println(String.format("hex %x, octal %o, sci %.2e", 255, 8, 12345.678));
System.out.println(String.format("bool %b, char %c, percent %%", true, 'J'));
System.out.println(String.format("reuse arg 1: %1$s and %1$s again", "echo"));
}
}
One pattern plus its arguments beats a long chain of plus signs.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.