How to use JDK 13’s String::formatted method

Yassin Hajaj
Aug 5 · 1 min read

JDK 13 introduces multiline strings to the Java programming language. This feature comes with util methods to go along with it. One of them is String::formatted .

Let’s test it out.

Before JDK 13, it was only possible to format a String with an invocation not done on the String itself :

new Formatter().format("%s, %s !", "Hello", "World")

String.format("%s, %s !", "Hello", "World")

It is now possible to use the template String directly as the source of the invocation

"%s, %s !".format("Hello", "World") will print Hello World ! as expected.

Tested in jshell with OpenJDK 13, it still gives a warning because of its @deprecated javadoc annotation

|  Warning:
| formatted(java.lang.Object...) in java.lang.String has been deprecated and marked for removal
| "%s, %s !".formatted("Hello", "World")
| ^------------------^
$12 ==> "Hello, World !"

But this is not a problem and will disappear once the JDK is officially released.

Yassin Hajaj
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade