Search

Dark theme | Light theme

March 11, 2021

Java Joy: Formatting A String Value With Formatted Method

Java 15 introduced the multi-line string value referred to as a text block. With this introduction also the formatted method was added to the String class. The method can be invoked on a String value directly and function exactly as the static String.format method. The nice thing is that now we directly can use a method on the value instead of having to use a static method where the value is passed as argument.

In the following example we use the formatted method for a normal String value and a text block:

package mrhaki.string;

public class Formatted {
    public static void main(String[] args) {
        String text = "Hi, %s, thank you for reading %d blogs".formatted("mrhaki", 2);
        assert "Hi, mrhaki, thank you for reading 2 blogs".equals(text);

        String email = """
        Hello %s,

        thank you for reading %d blogs.
        """.formatted("Hubert", 2);

        assert """
                Hello Hubert,

                thank you for reading 2 blogs.
                """.equals(email);
    }
}

Written with Java 15.