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}"nameSTR."Hello \{name}!"\{...}
The compiler did not glue the pieces together itself. It built a StringTemplate"Hello ""!"name
joined fragments and values into aSTR , like concatenation.String also read format specifiers such asFMT before each value.%,.2f returned the unprocessedRAW .StringTemplate
Anyone could write a processor, and it could return any type. A SQL processor could turn the values into PreparedStatement
| JDK | JEP | Status |
|---|---|---|
| 21 (September 2023) | JEP 430 | First preview |
| 22 (March 2024) | JEP 459 | Second preview |
| 23 (September 2024) | JEP 465, proposed to finalize | Closed / Withdrawn; the feature was removed from the JDK |
| 24 and 25 | none | Not 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 21java --enable-preview TemplatesOnJdk21
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("<", "<").replace(">", ">"));
}
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:
Hello Ana, total 1234.5
Hello Ana, total 1,234.50
fragments: [Hello , , total , ]
values: [Ana, 1234.5]
Comment: <b>hi</b>
printed theSTR asdouble does, 1234.5, whileDouble.toString appliedFMT and printed 1,234.50.%,.2f 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.RAW- The custom
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.HTML
Proof that templates are gone
The next program compiles a class that uses STR
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:
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\{STR
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.
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:
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
did. Since Java 9 (JEP 280), javac compilesSTR on strings to one+ call toinvokedynamic , which sizes the result once, so it is efficient even for many parts.StringConcatFactory andformatted appliedString.format : grouping and two decimals, the equivalent of%,.2f .FMT- With
the same pattern printedLocale.GERMANY . Without a locale,1.234,50 uses the JVM's default locale, so pass one explicitly for files other programs read.formatted uses numbered arguments, so translators can reorder them, andMessageFormat chooses the plural: "3 items" for Ana, "one item" for Ben.{1,choice,0#no items|1#one item|1<{1} items}- A text block with
handles multi-line output; seeformattedtext blocks .
MessageFormat and String.format traps
MessageFormat
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:
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
: a single quote starts a quoted section, so the apostrophe vanished and the placeholder was never replaced. Write two quotes,Dont forget {0} . This trap is common in translated resource bundles.Don''t - The year 2026 became "2,026" because numbers get grouping separators. Use
, or pass the value as a{0,number,#} as was done for the order number.String - A missing argument left
in the output silently.{1} threwString.format for the same mistake, which is easier to catch in tests.MissingFormatArgumentException
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
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("<");
case '>' -> sb.append(">");
case '&' -> sb.append("&");
case '"' -> sb.append(""");
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:
concatenated: Comment: nice post [script]steal()[/script]
escaped: Comment: nice post <script>steal()</script>
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
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):
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'='1PreparedStatement
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
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):
+ 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
took about the same time. WritingStringBuilder by hand no longer pays off for a single expression; it still helps when appending in a loop.StringBuilder 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.String.format 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.MessageFormat
Which one to use today
| Situation | Use |
|---|---|
| Short strings, log messages, exceptions | + |
| Numbers with decimals, padding or grouping | formattedString.format |
| Output for users in several countries | String.format(Locale, ...) |
| Translated messages with plurals | MessageFormat |
| Multi-line text | A text block with formatted |
| SQL with user values | PreparedStatement |
| HTML with user values | A template engine that escapes by default |
| JSON | A JSON library such as |
| Appending in a loop |
Migrating code written against the preview is mechanical. STR."Hi \{name}""Hi " + nameFMT."%.2f\{x}""%.2f".formatted(x)sql.query("SELECT * FROM t WHERE id = ?", id)
For format specifiers in detail, see