Java Snippet

Format Strings with String.format

Difficulty: Easy

`String.format` is Java's printf-style formatter for building human-readable strings without ad-hoc concatenation. This snippet covers the common conversions (`%s`, `%d`, `%.2f`, `%n`), padding and alignment for table layouts, and locale-aware vs locale-independent formatting. Reach for `String.format` for any output that mixes types or needs precise width control.

Code Snippets
/

Format Strings with String.format

Format Strings with String.format

`String.format` is Java's printf-style formatter for building human-readable strings without ad-hoc concatenation. This snippet covers the common conversions (`%s`, `%d`, `%.2f`, `%n`), padding and alignment for table layouts, and locale-aware vs locale-independent formatting. Reach for `String.format` for any output that mixes types or needs precise width control.

Java
Easy
3 snippets
strings
string-manipulation
java-string-builder

299 views

8

The format string contains conversion specifiers introduced by %. %s is the most general, calling toString() on whatever you pass. %d requires an integer, %f a floating-point number with optional precision (%.2f for two decimals), and %n emits the platform-correct line separator (use it instead of \n for portable output). String.format returns a String; System.out.printf writes directly to stdout using the same syntax.