50. String Templates (Preview)
String templates (JEP 430/459) embed expressions directly in strings with \{expr} syntax using a template processor โ safer than String.format because the processor validates and transforms the result before it becomes a string.
Explanation
String templates were introduced as a preview feature in Java 21 (JEP 430) and evolved through Java 22 (JEP 459). The key idea: a template processor (STR, FMT, or custom) receives both the literal string fragments and the interpolated values separately before forming the result โ enabling sanitisation, escaping, or type-safe transformation.
STR."Hello \{name}!" produces a String. FMT."Pi = %.5f\{Math.PI}" applies printf-style formatting. Custom processors can prevent SQL injection or XSS by escaping values before interpolating.
Note: the exact final syntax may change as the feature finishes standardisation. The preview in Java 21/22 uses STR."..." processor syntax. Later preview revisions may alter this. Always check the JEP for the current version you are using.
Example
// Requires --enable-preview and the appropriate Java version
// java --enable-preview --source 21 StringTemplatesDemo.java
public class StringTemplatesDemo {
public static void main(String[] args) {
String name = "Alice";
int age = 30;
double pi = Math.PI;
// STR processor: simple string interpolation
String greeting = STR."Hello, \{name}! You are \{age} years old.";
System.out.println(greeting);
// Hello, Alice! You are 30 years old.
// Expressions in templates
String calc = STR."Next year you will be \{age + 1}.";
System.out.println(calc);
// FMT processor: format specifiers
String formatted = FMT."Pi to 4 places: %.4f\{pi}";
System.out.println(formatted);
// Pi to 4 places: 3.1416
// Multi-line template (combined with text block syntax)
String report = STR."""
Name: \{name}
Age: \{age}
""";
System.out.print(report);
}
}Sources
- https://openjdk.org/jeps/430 โ JEP 430: String Templates (preview, Java 21)
- https://openjdk.org/jeps/459 โ JEP 459: String Templates (second preview, Java 22)