System.out.printf()
Prints a string built from a template with %s, %d, %.2f placeholders.
Available since: Java 5
Syntax
public PrintStream printf(String format, Object... args)Parameters
| Parameter | Type | Description |
|---|---|---|
| format | String | A template with placeholders, as in String.format(). |
| args | Object... | The values to insert. |
Return value
PrintStreamThe same System.out stream (usually ignored).
Examples
The line break must be added yourself — %n:
void main() {
System.out.printf("%s has %d messages%n", "Anna", 5);
System.out.printf("%-6s|%5d|%n", "Oleg", 42);
}Output:
Anna has 5 messages
Oleg | 42|Decimal numbers with an explicit locale — always with a dot:
void main() {
System.out.printf(Locale.ROOT, "Total: %.2f%n", 1234.5);
System.out.printf(Locale.ROOT, "Share: %.1f%%%n", 12.345);
}Output:
Total: 1234.50
Share: 12.3%Notes
printf() does not end the line — without %n the next output continues on the same line. The placeholders are the same as in String.format(). IO has no printf() — use IO.println("...".formatted(...)) there.
See also
- String.format() — Builds a string from a template with placeholders such as %s and %d.
- String.formatted() — Uses the string itself as a template and fills it in — a shorter form of String.format().
- System.out.println() — The classic way to print to the console: prints a value and ends the line.
Related recipes
In the tutorial
- Text blocks and formatting — Multi-line text blocks in Java, formatting strings with formatted, String.format and printf, the %s, %d and %f specifiers and field width.