String.formatted()
Code Comparison
String msg = String.format(
"Hello %s, you are %d",
name, age
);
String msg =
"Hello %s, you are %d"
.formatted(name, age);
Why the modern way wins
๐
Reads naturally
Template.formatted(args) flows better than String.format(template, args).
๐
Chainable
Can be chained with other string methods.
๐
Less verbose
Drops the redundant String.format() static call.
Old Approach
String.format()
Modern Approach
formatted()
JDK Support
String.formatted()
Available
Widely available since JDK 15 (Sept 2020)
How it works
String.formatted() is an instance method equivalent to String.format() but called on the format string. It reads more naturally in a left-to-right flow.
Related Documentation
Proof