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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
