String.formatted()
Uses the string itself as a template and fills it in — a shorter form of String.format().
Available since: Java 15
Syntax
public String formatted(Object... args)Parameters
| Parameter | Type | Description |
|---|---|---|
| args | Object... | The values to insert, in order. |
Return value
StringThe formatted string.
Examples
Same as String.format(), but called on the template:
void main() {
String line = "%s: %d points".formatted("Oleg", 42);
IO.println(line);
}Output:
Oleg: 42 pointsHandy with text blocks:
void main() {
String card = """
Name: %s
Items: %d
""".formatted("Anna", 3);
IO.print(card);
}Output:
Name: Anna
Items: 3Notes
The placeholders are the same as in String.format(). As there, the decimal format depends on the system language.
See also
- String.format() — Builds a string from a template with placeholders such as %s and %d.
- Text block """ — A multi-line string literal in triple quotes.
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.