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

August 05, 2019

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.