Java TextBlocks and String#replace

The (JDK 1.5) method String#replace is useful for the substitution of multiple occurrences of a placeholder.

In the following sample, two occurrences of the $name String were replaced with a single replace invocation:

public void textBlocks() {
    var message = """
        class $class{
            String $name;

            public String toString(){
                return this.$name;
        """.replace("$class", "Developer")
           .replace("$name", "firstName");


class Developer{
    String firstName;

    public String toString(){
        return this.firstName;

The old, JDK 1.5, String#replace method is useful for replacement of multiple placeholders with a single call, whereby the newer JDK 15 method: String#formatted relies on the Formatter syntax.

This post was inspired by the description of the: JEP 378: Text Blocks


Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments