String.format / printf & escape sequences
Format specifiers, padding and precision, escape sequences, and printf vs format.
Formatted output
Java borrows C-style format strings. System.out.printf(fmt, args...) prints a formatted line; String.format(fmt, args...) returns the formatted text as a String (handy for building a log line). Both take a *format string* containing format specifiers that each consume one argument.
A specifier has the shape %[flags][width][.precision]conversion:
- %d — decimal integer
- %f — floating-point (default 6 decimals)
- %s — string (calls the argument's toString)
- %c — character
- %b — boolean
- %x — hexadecimal
- %n — platform-independent newline (prefer it over \n in format strings)
- %% — a literal percent sign
Worked example. Format a log line with a fixed-width label and two decimals.
String line = String.format("[%-8s] temp=%6.2f%n", "SENSOR", 21.5);
// [SENSOR ] temp= 21.50\n
Reading that format string left to right:
- %-8s — the string "SENSOR" in a field 8 wide, - means left-justified, so it is padded on the right to "SENSOR ".
- temp= — literal text, printed as-is.
- %6.2f — the double 21.5 in a field 6 wide with 2 decimals: " 21.50" (a leading space pads to width 6).
- %n — a newline.
Escape sequences
Inside a string literal, a backslash introduces an escape sequence: \n newline, \t tab, \" a literal double-quote, \\ a literal backslash, \' a single quote, \r carriage return. To put a Windows path in a string you must double every backslash: "C:\\temp\\out.txt".