The String::formatted method in Java is a concise way to format strings using placeholders, similar to the String::format method but with a cleaner syntax. It was introduced in Java 15, and it allows you to replace placeholders in a string with specified values.
The syntax of the formatted method is straightforward:
String formattedString = "Your name is %s and your age is %d".formatted("John", 25);
Here’s how it works:
- The placeholders in the string (such as
%s,%d) follow the same format specifiers as used inString.format().%s: Formats strings.%d: Formats integers.%f: Formats floating-point numbers.- And so on.
- The
formatted()method takes the format arguments in the exact order of appearance of the placeholders.
Example Usage:
Here are a few examples illustrating the different use cases:
Example 1: Format a simple text
String result = "Hello, %s!".formatted("Alice");
System.out.println(result);
// Output: Hello, Alice!
Example 2: Combine multiple placeholders
String summary = "Product: %s, Quantity: %d, Price: $%.2f".formatted("Widget", 10, 9.99);
System.out.println(summary);
// Output: Product: Widget, Quantity: 10, Price: $9.99
Example 3: Use with text blocks
In text blocks, you can similarly use the formatted method to insert values dynamically:
String jsonTemplate = """
{
"name": "%s",
"age": %d,
"email": "%s"
}
""";
String json = jsonTemplate.formatted("John", 30, "[email protected]");
System.out.println(json);
// Output:
// {
// "name": "John",
// "age": 30,
// "email": "[email protected]"
// }
Key Points:
- The
formattedmethod is directly callable on the string you want to format, making the code cleaner. - It has the same capabilities as
String.format, so it supports all format specifiers. formattedworks particularly well with text blocks for clean and readable multi-line string formatting.
This method is helpful for writing concise and fluent code without the need to call String.format explicitly.
