Format Specifiers: %s, %d, %f, and More
What you'll learn: How to use format specifiers with printf to control how strings, integers, and floating-point numbers appear in your output.
What Are Format Specifiers?
Format specifiers are placeholder codes that tell printf and format methods how to convert and display values. Think of them as templates: you write "Total: $%.2f" and Java replaces %.2f with your number, formatted to exactly two decimal places.
Common Specifiers
%s – Inserts a string (or any object, via toString())
writer.printf("Hello, %s!", "World");
// Output: Hello, World!
%d – Inserts a decimal integer
writer.printf("Count: %d", 42);
// Output: Count: 42
%f – Inserts a floating-point number
writer.printf("Price: %f", 19.99);
// Output: Price: 19.990000
Controlling Width and Precision
You can add numbers between the % and the letter to control formatting:
Width: Minimum number of characters to use
writer.printf("|%5d|", 42);
// Output: | 42| (padded to 5 chars)
Precision for floats: Number of decimal places
writer.printf("%.2f", 19.99);
// Output: 19.99
writer.printf("%.1f", 3.14159);
// Output: 3.1
Combined width and precision:
writer.printf("%8.2f", 19.99);
// Output: " 19.99" (8 chars total, 2 decimals)
Other Useful Specifiers
- %n – Platform-specific newline (better than
\n) - %b – Boolean value
- %x – Hexadecimal integer
Key Takeaway: Format specifiers like %s, %d, and %f let you precisely control how data appears in formatted output, with optional width and precision modifiers for alignment and decimal control.