String templates: what happened and what to use instead

String templates added interpolation such as STR."Hello \{name}" to Java as a preview in JDK 21 and 22. The feature was withdrawn before becoming final and is not in any current JDK. This page explains how templates were designed and why that design mattered, proves with the compiler that they are gone, and covers the standard ways to build strings today, with their traps and costs.

Contents

What string templates were

Many languages have string interpolation: writing "Hello ${name}" and getting the value of name inside the text. Java never had it. The string templates proposal added it with a twist aimed at safety. A template expression had two parts, a processor and a template, written STR."Hello \{name}!", where \{...} embeds any Java expression.

The compiler did not glue the pieces together itself. It built a StringTemplate object holding the literal fragments ("Hello " and "!") and the values (name) in separate lists, and passed it to the processor. Three processors came with the JDK:

  • STR joined fragments and values into a String, like concatenation.
  • FMT also read format specifiers such as %,.2f before each value.
  • RAW returned the unprocessed StringTemplate.

Anyone could write a processor, and it could return any type. A SQL processor could turn the values into PreparedStatement parameters, and an HTML processor could escape them. That separation of trusted text from untrusted values was the main reason for the design: interpolation that is safe against injection by construction.

History of string templates
JDKJEPStatus
21 (September 2023)JEP 430First preview
22 (March 2024)JEP 459Second preview
23 (September 2024)JEP 465, proposed to finalizeClosed / Withdrawn; the feature was removed from the JDK
24 and 25noneNot available, even with --enable-preview

The OpenJDK team withdrew the feature because they were not satisfied with the design, in particular the processor syntax, and preferred to rethink it rather than freeze it. A redesigned version may return in a future release, but none has been targeted. The rest of this page shows the preview running on JDK 21, proves it is gone in JDK 25, and covers what to use today. The programs other than the historical one were compiled and run on JDK 25.

What the preview looked like on JDK 21

This program uses all three built-in processors and a custom one. It compiles only on JDK 21 or 22 with --enable-preview --release 21 (or 22), so it is shown as a historical record. The output is from a real run on JDK 21.0 with java --enable-preview TemplatesOnJdk21.

Java
import static java.util.FormatProcessor.FMT;

import java.util.List;

// Runs only on JDK 21 or 22 with --enable-preview: the feature was removed in JDK 23
public class TemplatesOnJdk21 {

    // A custom processor: escapes every embedded value for HTML
    static final StringTemplate.Processor<String, RuntimeException> HTML = st -> {
        StringBuilder sb = new StringBuilder();
        List<String> fragments = st.fragments();
        List<Object> values = st.values();
        for (int i = 0; i < values.size(); i++) {
            sb.append(fragments.get(i));
            sb.append(String.valueOf(values.get(i)).replace("<", "&lt;").replace(">", "&gt;"));
        }
        return sb.append(fragments.get(values.size())).toString();
    };

    public static void main(String[] args) {
        String name = "Ana";
        double total = 1234.5;
        System.out.println(STR."Hello \{name}, total \{total}");
        System.out.println(FMT."Hello %s\{name}, total %,.2f\{total}");

        StringTemplate raw = StringTemplate.RAW."Hello \{name}, total \{total}";
        System.out.println("fragments: " + raw.fragments());
        System.out.println("values:    " + raw.values());

        String comment = "<b>hi</b>";
        System.out.println(HTML."Comment: \{comment}");
    }
}

Output on JDK 21 with preview features enabled:

Output
Hello Ana, total 1234.5
Hello Ana, total 1,234.50
fragments: [Hello , , total , ]
values:    [Ana, 1234.5]
Comment: &lt;b&gt;hi&lt;/b&gt;
  • STR printed the double as Double.toString does, 1234.5, while FMT applied %,.2f and printed 1,234.50.
  • RAW shows the data a processor receives: three fragments and two values. There is always one more fragment than values, which is why the custom processor appends the last fragment after the loop.
  • The custom HTML processor escaped the angle brackets of the value but would have left the template's own text alone. That is the property plain concatenation cannot offer.

Proof that templates are gone

The next program compiles a class that uses STR with the compiler of the JDK that runs it, with preview features enabled for that JDK's own version, and prints javac's verdict.

Java
import java.net.URI;
import java.util.List;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;

// Compiles the Java 21/22 preview syntax with the running JDK and prints javac's verdict
public class TemplatesGone {

    public static void main(String[] args) {
        String code = """
                class Demo {
                    String greet(String name) {
                        return STR."Hello \\{name}!";
                    }
                }
                """;
        JavaFileObject file = new SimpleJavaFileObject(URI.create("string:///Demo.java"),
                JavaFileObject.Kind.SOURCE) {
            @Override
            public CharSequence getCharContent(boolean ignore) {
                return code;
            }
        };
        String release = Integer.toString(Runtime.version().feature());
        JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
        DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<>();
        boolean ok = javac.getTask(null, null, diags,
                List.of("--enable-preview", "--release", release, "-d",
                        System.getProperty("java.io.tmpdir")),
                null, List.of(file)).call();
        System.out.println("JDK " + release + " with --enable-preview: "
                + (ok ? "compiles" : "does not compile"));
        diags.getDiagnostics().stream()
                .filter(d -> d.getKind() == javax.tools.Diagnostic.Kind.ERROR)
                .forEach(d -> System.out.println("  line " + d.getLineNumber() + ": "
                        + d.getMessage(null)));
    }
}

Output on JDK 25:

Output
JDK 25 with --enable-preview: does not compile
  line 3: illegal escape character

Run on JDK 21, the same program prints JDK 21 with --enable-preview: compiles. On JDK 25 the error is "illegal escape character": \{ was an escape sequence that existed only for templates, so with the feature gone the lexer rejects it before it even reaches the unknown name STR. Code written against the preview does not compile on any current JDK and must be rewritten with one of the approaches below.

The standard alternatives

The program builds the same order summary five ways. The total 1234.5 needs a thousands separator and has only one decimal digit, which shows how each approach handles number formatting.

Java
import java.text.MessageFormat;
import java.util.Locale;

public class Alternatives {

    record Order(String customer, int items, double total) {
    }

    public static void main(String[] args) {
        Order o = new Order("Ana", 3, 1234.5);

        // 1. Concatenation: javac turns this into a single optimized call (JEP 280)
        String a = "Hi " + o.customer() + ", " + o.items() + " items, total " + o.total();

        // 2. String.format / formatted: placeholders with formatting control
        String b = "Hi %s, %d items, total %,.2f".formatted(o.customer(), o.items(), o.total());

        // 3. Locale-aware formatting: same pattern, German conventions
        String c = String.format(Locale.GERMANY, "Hi %s, %d items, total %,.2f",
                o.customer(), o.items(), o.total());

        // 4. MessageFormat: numbered arguments and a choice format for plurals
        MessageFormat mf = new MessageFormat(
                "Hi {0}, {1,choice,0#no items|1#one item|1<{1} items}, total {2,number,#,##0.00}",
                Locale.US);
        String d = mf.format(new Object[] {o.customer(), o.items(), o.total()});
        String e = mf.format(new Object[] {"Ben", 1, 9.99});

        // 5. A text block with formatted() for multi-line output
        String f = """
                Customer: %s
                Items:    %d
                Total:    %,.2f""".formatted(o.customer(), o.items(), o.total());

        System.out.println("1 concat:        " + a);
        System.out.println("2 formatted:     " + b);
        System.out.println("3 Locale.GERMANY: " + c);
        System.out.println("4 MessageFormat: " + d);
        System.out.println("  one item:      " + e);
        System.out.println("5 text block:\n" + f);
    }
}

Output:

Output
1 concat:        Hi Ana, 3 items, total 1234.5
2 formatted:     Hi Ana, 3 items, total 1,234.50
3 Locale.GERMANY: Hi Ana, 3 items, total 1.234,50
4 MessageFormat: Hi Ana, 3 items, total 1,234.50
  one item:      Hi Ben, one item, total 9.99
5 text block:
Customer: Ana
Items:    3
Total:    1,234.50
  • Concatenation printed 1234.5, exactly like STR did. Since Java 9 (JEP 280), javac compiles + on strings to one invokedynamic call to StringConcatFactory, which sizes the result once, so it is efficient even for many parts.
  • formatted and String.format applied %,.2f: grouping and two decimals, the equivalent of FMT.
  • With Locale.GERMANY the same pattern printed 1.234,50. Without a locale, formatted uses the JVM's default locale, so pass one explicitly for files other programs read.
  • MessageFormat uses numbered arguments, so translators can reorder them, and {1,choice,0#no items|1#one item|1<{1} items} chooses the plural: "3 items" for Ana, "one item" for Ben.
  • A text block with formatted handles multi-line output; see text blocks.

MessageFormat and String.format traps

MessageFormat is the standard choice for translated messages, but its syntax has surprises that compile and run without any error. The inputs were picked to trigger each one: an apostrophe, a year, and a missing argument.

Java
import java.text.MessageFormat;
import java.util.Locale;

public class MessageFormatTraps {

    public static void main(String[] args) {
        Locale.setDefault(Locale.US);

        // 1. A single quote starts a quoted section: the placeholder is not replaced
        System.out.println(MessageFormat.format("Don't forget {0}", "Ana"));
        System.out.println(MessageFormat.format("Don''t forget {0}", "Ana"));

        // 2. Numbers get grouping separators, which looks wrong for years and IDs
        System.out.println(MessageFormat.format("Year {0}, order {1}", 2026, 1234567));
        System.out.println(MessageFormat.format("Year {0,number,#}, order {1}", 2026,
                String.valueOf(1234567)));

        // 3. A missing argument is printed as the placeholder, not as an error
        System.out.println(MessageFormat.format("{0} bought {1} items", "Ben"));

        // 4. String.format is stricter: a missing argument throws
        try {
            System.out.println(String.format("%s bought %d items", "Ben"));
        } catch (java.util.MissingFormatArgumentException e) {
            System.out.println("String.format: MissingFormatArgumentException " + e.getMessage());
        }
    }
}

Output:

Output
Dont forget {0}
Don't forget Ana
Year 2,026, order 1,234,567
Year 2026, order 1234567
Ben bought {1} items
String.format: MissingFormatArgumentException Format specifier '%d'
  • "Don't forget {0}" printed Dont forget {0}: a single quote starts a quoted section, so the apostrophe vanished and the placeholder was never replaced. Write two quotes, Don''t. This trap is common in translated resource bundles.
  • The year 2026 became "2,026" because numbers get grouping separators. Use {0,number,#}, or pass the value as a String as was done for the order number.
  • A missing argument left {1} in the output silently. String.format threw MissingFormatArgumentException for the same mistake, which is easier to catch in tests.

Injection: the problem templates were meant to solve

With plain string building, a value containing markup or SQL becomes part of the markup or SQL. Without template processors, the rule is to handle values at the boundary yourself. The first program shows the HTML case with a comment containing a script tag; the small render method keeps the template text and the values apart, the same idea as a processor, and escapes each value it inserts.

Java
import java.util.Map;

public class EscapeAtTheEdge {

    // What templates promised: the processor sees literal text and values separately.
    // Without templates, escape each value yourself before it enters the string.
    static String html(String s) {
        StringBuilder sb = new StringBuilder(s.length());
        for (char ch : s.toCharArray()) {
            switch (ch) {
                case '<' -> sb.append("&lt;");
                case '>' -> sb.append("&gt;");
                case '&' -> sb.append("&amp;");
                case '"' -> sb.append("&quot;");
                default -> sb.append(ch);
            }
        }
        return sb.toString();
    }

    // A tiny named-placeholder renderer that escapes every value it inserts
    static String render(String template, Map<String, String> values) {
        String out = template;
        for (Map.Entry<String, String> e : values.entrySet()) {
            out = out.replace("${" + e.getKey() + "}", html(e.getValue()));
        }
        return out;
    }

    public static void main(String[] args) {
        String comment = "nice post <script>steal()</script>";
        String unsafe = "Comment: " + comment;
        String safe = render("Comment: ${comment}", Map.of("comment", comment));
        // angle brackets are shown as [ ] so this page does not render the tag
        System.out.println("concatenated: " + unsafe.replace('<', '[').replace('>', ']'));
        System.out.println("escaped:      " + safe);
    }
}

Output:

Output
concatenated: Comment: nice post [script]steal()[/script]
escaped:      Comment: nice post &lt;script&gt;steal()&lt;/script&gt;

In the concatenated version the script tag survives intact (shown with square brackets so this page does not run it). In the rendered version it became text that a browser displays instead of executing. For real pages, use a template engine that escapes by default rather than a hand-written render.

SQL is the more dangerous case. The second program uses an in-memory H2 database with two users and a login value typed by an attacker, built once into the SQL text with formatted and once passed as a parameter.

Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class SqlInjection {

    public static void main(String[] args) throws SQLException {
        try (Connection db = DriverManager.getConnection("jdbc:h2:mem:shop")) {
            try (Statement st = db.createStatement()) {
                st.execute("CREATE TABLE users(name VARCHAR(20), secret VARCHAR(20))");
                st.execute("INSERT INTO users VALUES ('ana', 'a-123'), ('ben', 'b-456')");
            }
            String input = "nobody' OR '1'='1";             // typed into a login form

            // Building SQL text from the value: the quote ends the string literal early
            String sql = "SELECT name, secret FROM users WHERE name = '%s'".formatted(input);
            System.out.println("SQL sent: " + sql);
            try (Statement st = db.createStatement(); ResultSet rs = st.executeQuery(sql)) {
                while (rs.next()) {
                    System.out.println("  leaked: " + rs.getString(1) + " " + rs.getString(2));
                }
            }

            // A parameter is sent separately from the SQL text and is never parsed as SQL
            try (PreparedStatement ps =
                    db.prepareStatement("SELECT name, secret FROM users WHERE name = ?")) {
                ps.setString(1, input);
                try (ResultSet rs = ps.executeQuery()) {
                    int rows = 0;
                    while (rs.next()) {
                        rows++;
                    }
                    System.out.println("PreparedStatement rows: " + rows);
                }
            }
        }
    }
}

Output (H2 2.3 in memory, on the classpath):

Output
SQL sent: SELECT name, secret FROM users WHERE name = 'nobody' OR '1'='1'
  leaked: ana a-123
  leaked: ben b-456
PreparedStatement rows: 0

The quote in nobody' OR '1'='1 closed the string literal early, so the condition became "name is nobody, or 1 equals 1", which is true for every row, and both secrets leaked. With PreparedStatement, the value was sent separately from the SQL text and compared as an ordinary string, so 0 rows matched. This is exactly what a SQL template processor would have done automatically. See PreparedStatement for more.

How fast is each way of building a string?

The program builds one million short messages with each approach. Each runs 3 times after a warm-up round and the fastest run is reported. This is a rough comparison, not a benchmark; see the JMH page for proper measurement.

Java
import java.text.MessageFormat;
import java.util.Locale;

public class BuildSpeed {

    interface Builder {
        String build(String name, int n);
    }

    public static void main(String[] args) {
        MessageFormat mf = new MessageFormat("user {0} has {1} items", Locale.US);
        for (int round = 0; round < 2; round++) {                 // round 0 is warm-up
            boolean print = round == 1;
            time("+ concatenation", (s, n) -> "user " + s + " has " + n + " items", print);
            time("StringBuilder", (s, n) -> new StringBuilder("user ").append(s)
                    .append(" has ").append(n).append(" items").toString(), print);
            time("String.format", (s, n) -> String.format("user %s has %d items", s, n), print);
            time("MessageFormat", (s, n) -> mf.format(new Object[] {s, n}), print);
        }
    }

    static void time(String label, Builder b, boolean print) {
        long best = Long.MAX_VALUE;
        long chars = 0;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            chars = 0;
            for (int i = 0; i < 1000000; i++) {
                chars += b.build("ana", i).length();
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        if (print) {
            System.out.printf("%-16s %,d chars  best of 3: %,5d ms%n", label, chars,
                    best / 1000000);
        }
    }
}

Output (2-CPU Linux machine, JDK 25; absolute times will differ on yours):

Output
+ concatenation  24,888,890 chars  best of 3:    13 ms
StringBuilder    24,888,890 chars  best of 3:    12 ms
String.format    24,888,890 chars  best of 3:   157 ms
MessageFormat    25,887,890 chars  best of 3:   393 ms
  • Concatenation and StringBuilder took about the same time. Writing StringBuilder by hand no longer pays off for a single expression; it still helps when appending in a loop.
  • String.format was roughly ten times slower, because it parses the format string on every call. That is irrelevant for a log line or a report, but noticeable in a hot loop.
  • MessageFormat was slower still, and produced about a million more characters: it inserted grouping separators into the numbers above 999, the same trap as the year above.

Which one to use today

Choosing a way to put values into text
SituationUse
Short strings, log messages, exceptions+ concatenation
Numbers with decimals, padding or groupingformatted or String.format
Output for users in several countriesString.format(Locale, ...)
Translated messages with pluralsMessageFormat with resource bundles, quotes doubled
Multi-line textA text block with formatted
SQL with user valuesPreparedStatement parameters, never string building
HTML with user valuesA template engine that escapes by default
JSONA JSON library such as Jackson
Appending in a loopStringBuilder

Migrating code written against the preview is mechanical. STR."Hi \{name}" becomes "Hi " + name. FMT."%.2f\{x}" becomes "%.2f".formatted(x). A custom processor becomes an ordinary method that takes the fixed text and the values as separate parameters, such as sql.query("SELECT * FROM t WHERE id = ?", id), which keeps the one benefit that mattered: untrusted values never become part of the trusted text.

For format specifiers in detail, see string formatting.