String Templates
1. What are String Templates?
String Templates are a preview feature (Java 21, refined in Java 22) that allow embedding expressions into strings safely and declaratively.
Think of it as:
String interpolation + validation + processing2. Problem Before String Templates
Before Java 21:
String concatenation
String name = "Nazeer";
String s = "Hello " + name;String.format (unsafe, error-prone)
String s = String.format("Hello %s", name);Problems:
- No compile-time validation
- SQL injection risks
- Hard to read for complex strings
3. Basic Syntax (Core Concept)
String name = "Nazeer";
String message = STR."Hello {name}";STR → template processor\{} → embedded expression
4. Key Components
4.1 Template Expression
STR."Hello {name}"Breakdown:
STR→ processor"Hello \{name}"→ template\{name}→ expression
4.2 Template Processor
Acts like an interpreter for templates
String result = STR."Value = {10 + 20}";Output:
Value = 305. Built-in Processors
5.1 STR (Default)
String s = STR."Sum = {10 + 20}";Equivalent to:
“Sum = “ + (10 + 20);
5.2 RAW (Advanced)
StringTemplate template = RAW."Hello {name}";Gives:
- fragments
- values
Used for custom processing
6. Multiple Expressions
String name = "Nazeer";
int age = 30;
String s = STR."{name} is {age} years old";Clean & readable
7. Expressions Power (Very Important)
String result = STR."Square = {Math.pow(5,2)}";
String result = STR."Upper = {name.toUpperCase()}";Any Java expression allowed
8. Multi-line Templates
String sql = STR."""
SELECT *
FROM users
WHERE name = {name}
""";Combines:
- text blocks
- interpolation
9. The Real Power: Custom Processors
This is where String Templates shine (interview gold)
Example: SQL Injection Safe Processor
StringTemplate.Processor<String, RuntimeException> SQL =
template -> {
StringBuilder sb = new StringBuilder();
Iterator<String> fragments = template.fragments().iterator();
Iterator<Object> values = template.values().iterator();
while (fragments.hasNext()) {
sb.append(fragments.next());
if (values.hasNext()) {
sb.append("?"); // replace with placeholder
}
}
return sb.toString();
};
String query = SQL."SELECT * FROM users WHERE name = {name}";Output:
SELECT * FROM users WHERE name = ?Prevents SQL injection
Example: Logging Template
var LOG = StringTemplate.Processor.of(
template -> template.interpolate()
);
String msg = LOG."User {name} logged in at {System.currentTimeMillis()}";10. StringTemplate API (Important)
Core Interface
public interface StringTemplate {
List<String> fragments();
List<Object> values();
}Example
StringTemplate st = RAW."Hello {name}";Gives:
fragments: [“Hello “, “”]
Get Syed Nazeer’s stories in your inbox
Join Medium for free to get updates from this writer.
values: [“Nazeer”]
11. Internal Working (Senior-Level Insight)
Template:
"Hello \{name}"Becomes:
- fragments → [“Hello “, “”]
- values → [name]
Processor:
combine(fragments, values)12. Security Advantage
Without templates (danger)
String query = "SELECT * FROM users WHERE name = '" + name + "'";SQL Injection risk
With templates + processor
SQL."SELECT * FROM users WHERE name = {name}";Safe parameter binding
13. Performance Consideration
Compiled efficiently → no major overhead
14. Limitations (Important)
Preview Feature
- Java 21 → Preview
- Java 22 → Preview (refined)
- May change in future
Must enable preview
— enable-preview — release 21
Not widely adopted yet
- Limited framework support
15. Real-World Use Cases
1. SQL Queries
SQL."SELECT * FROM orders WHERE id = {id}";2. JSON Building
String json = STR."""
{
"name": "{name}",
"age": {age}
}
""";3. Logging
logger.info(STR."User {userId} logged in");4. REST Responses
return STR."Hello {user.getName()}";16. Comparison
String Templates vs String.format
Template vs Concatenation
17. Best Practices (Architect Level)
1. Use STR for simple interpolation
STR.”Hello {name}”
2. Use custom processors for security-critical code
- SQL
- HTML
- Logging
3. Avoid business logic inside templates
// Bad
STR."{user.calculateSalary()}"// Better
var salary = user.calculateSalary();
STR."Salary: {salary}"4. Use with Text Blocks for DSLs
18. Interview Questions
What problem do String Templates solve?
Safe, readable, extensible string interpolation
Difference between STR and RAW?
STRRAWReturns StringReturns StringTemplateImmediate processingDeferred processing
Are String Templates safe by default?
Only with a proper processor
Can we replace String.format?
Mostly yes (cleaner + safer)
19. Future Direction
- Likely stable in upcoming Java versions
- Integration with:
- SQL APIs
- JSON libraries
- Logging frameworks
Final Summary
Architect-Level Insight
String Templates are not just interpolation. They introduce:
String + Data + Processor = Safe DSL Engine





