Lesson · Strings & Text
Formatting: printf, String.format and text blocks
12 min readFormatting
printf's conversion language, the alignment and precision flags that make output legible, and text blocks for embedding multi-line text without escape soup.
printf and the conversion language
System.out.printf(format, args...) and String.format(format, args...) share one grammar: a format string with % conversions, arguments consumed in order. %d integers, %f floating point, %s any object via toString, %b boolean, %c char, %n the platform line separator (prefer it over a literal newline in format strings).
A printf without a newline at the end leaves the cursor mid-line; print and println are printf's simpler siblings, and choosing among them is a habit, not a rule. String.format produces a string for use anywhere (logs, exceptions, files); printf writes to an Appendable, usually stdout.
Width, precision, alignment
A conversion can carry width and precision: %8.2f is at least 8 wide with 2 digits after the point. The width pads with spaces on the left by default; the - flag pads on the right: %-8s left-aligns within 8. %,d inserts thousands separators, %04d zero-pads, %+d always shows the sign. A table of aligned columns is one format pass: %10s %8.2f%n.
Precision means different things per conversion: digits after the point for floats, maximum characters for strings (%.5s truncates), significant digits for generic floats (%g). And the whole language is locale-aware at the edges: %f uses the default locale's decimal separator (a comma in much of Europe), which is right for humans and wrong for machine-readable output. Locale.ROOT pins it when the output is data.
The traps
A mismatch between conversion and argument throws IllegalFormatConversionException at runtime, not compile time: %d with a String fails when reached. More often, though, mismatches compile and merely misprint: %f with an int is fine (promotion), but passing the arguments in the wrong order prints amounts as ages and compiles forever. Named access is not part of the grammar; order is the contract.
Mixing %n and \n is subtler: %n is the platform's line separator (CRLF on Windows), and hard-coded \n produces UNIX line endings everywhere. For files consumed by other machines, pick one deliberately. And every % needs a conversion: a stray percent sign in the format string must be written %%.
Text blocks: multi-line strings without the noise
A text block opens with three quotes and a line break, includes the lines verbatim, and closes with three quotes. Common leading whitespace is stripped based on the least-indented line (and the closing delimiter's position), so indenting the block to match your code does not indent the value. Since Java 15 it is the normal way to embed SQL, JSON, HTML or long help text.
.formatted(args) and String.format work with them too: """...%d...""".formatted(count) keeps the readability of the block and the conversions of printf. Escapes mostly become literal (a quote inside needs care only next to the delimiters), and \ at a line end suppresses the newline when you need to join lines with indentation.
Width pads left; - pads right
In %8s the text sits at the right edge of an 8-wide field (numbers stay aligned). Add the minus: %-8s sits at the left edge (labels stay aligned). Column alignment in console output is exactly this flag, applied per column, and %n ends each row.
Interview angles
printf versus String.format?+
Same format grammar; printf writes into an output stream (and returns PrintStream), String.format returns a formatted String for any use. Use String.format in messages and logs; printf for direct console output.
What does %n do?+
Emits the platform line separator: \r\n on Windows, \n elsewhere. It keeps output correct per platform, where a literal \n is always a Unix newline. Files meant for other systems might still prefer the explicit \n for portability of CONTENT.
How do text blocks handle indentation?+
The minimal indentation across non-blank lines (and the closing delimiter) is stripped from every line. Indent the source to match surrounding code; the value stays flush. Trailing whitespace handling and the \ escape at line ends give fine control when needed.