String.format()
Builds a string from a template with placeholders such as %s and %d.
Available since: Java 5
Syntax
static String format(String format, Object... args)Parameters
| Parameter | Type | Description |
|---|---|---|
| format | String | The template: %s is a string, %d an integer, %f a decimal number, %n a line break. |
| args | Object... | The values to insert, in order. |
Return value
StringThe formatted string.
Examples
The main placeholders:
void main() {
String s = String.format("%s is %d years old", "Anna", 30);
IO.println(s);
}Output:
Anna is 30 years oldDecimal numbers: %.2f rounds to two places, and the locale sets the separator:
void main() {
IO.println(String.format(Locale.ROOT, "Price: %.2f", 9.5));
IO.println(String.format(Locale.GERMANY, "Price: %.2f", 9.5));
IO.println(String.format(Locale.ROOT, "%,d", 1234567));
}Output:
Price: 9.50
Price: 9,50
1,234,567Field width and alignment — a table:
void main() {
IO.println(String.format("%-8s|%6d|", "apples", 12));
IO.println(String.format("%-8s|%6d|", "kiwi", 150));
IO.println(String.format("%05d", 42));
}Output:
apples | 12|
kiwi | 150|
00042Notes
Common patterns: %.2f gives two decimal places, %10s a width of 10 aligned right, %-10s aligned left, %,d thousands separators, %x hexadecimal, %% a percent sign itself.
Without a locale argument the decimal separator comes from the system language: on a German or Russian computer %.2f gives 9,50. To always get a dot, pass Locale.ROOT as the first argument. If a value does not fit the placeholder (%d for a string), you get IllegalFormatConversionException.
See also
- String.formatted() — Uses the string itself as a template and fills it in — a shorter form of String.format().
- System.out.printf() — Prints a string built from a template with %s, %d, %.2f placeholders.
- NumberFormat — Formats numbers, money and percentages by the rules of a chosen country.
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.