Java / Java 21 Interview Questions
What are String Templates in Java 21 (Preview) and how do they improve string interpolation?
JEP 430 introduces String Templates as a preview feature in Java 21. They provide type-safe string interpolation via template processors — a safer alternative to string concatenation and String.format() that prevents injection vulnerabilities by separating the template structure from the values.
// Traditional approaches — error-prone
String name = "Alice";
int age = 30;
String s1 = "Hello " + name + ", you are " + age + " years old.";
String s2 = String.format("Hello %s, you are %d years old.", name, age);
String s3 = "Hello %s, you are %d years old.".formatted(name, age);
// String Template (Java 21 Preview) — requires --enable-preview
String s4 = STR."Hello \{name}, you are \{age} years old.";
// Embedded expressions are evaluated and inserted
// Expressions can be any Java expression
String s5 = STR."The sum of 3+4 is \{3+4}.";
String s6 = STR."First name: \{name.split(" ")[0]}";
// Multi-line template with STR
String json = STR."""
{
"name": "\{name}",
"age": \{age}
}
""";
// FMT processor — formatted output like printf
String formatted = FMT."Total: %10.2f\{total} USD";
// Custom template processor — safe SQL (not yet in preview)
// PreparedStatement ps = SQL."SELECT * FROM users WHERE id = \{userId}";
// The SQL processor parameterises the value — injection-safeThe key safety property: unlike simple string interpolation in other languages, String Templates allow custom processors (STR, FMT, or user-defined) to control how embedded values are combined with the template. A SQL processor can automatically use prepared statement parameters; a JSON processor can escape values correctly — the template structure and values are never naively concatenated.
More Related questions...