Java String Templates

Introduction

Before the introduction of String Templates, Java developers primarily used string concatenation (+), String.format(), MessageFormat, or StringBuilder to create dynamic strings. While these approaches work, they can become verbose, difficult to read, and prone to errors, especially when dealing with multiple variables or multi-line content.

To simplify string interpolation, Java introduced String Templates as a preview feature in Java 21 (JEP 430). They provide a safer, cleaner, and more expressive way to embed Java expressions directly inside string literals.

Note: As of Java 21, String Templates are still a preview feature, meaning they are not yet a permanent part of the Java language. Developers must enable preview features to use them, and the syntax may change in future Java releases.

What are Java String Templates?

A String Template is a language feature that allows you to embed Java expressions directly inside a string literal. Instead of manually concatenating strings using the + operator, you can write placeholders that are automatically evaluated and inserted into the final string.

For example, instead of writing:


String name = "John";
int age = 25;
String message = "Name: " + name + ", Age: " + age;

With String Templates, you can write:


String name = "John";
int age = 25;
String message = STR."Name: \{name}, Age: \{age}";

The result is:


Name: John, Age: 25

This syntax is more readable and easier to maintain.

Why Were String Templates Introduced?

Traditional string creation has several limitations:

  • Too much string concatenation
  • Difficult to read
  • Error-prone
  • Hard to maintain
  • Poor handling of multi-line strings

String Templates solve these issues by providing:

  • Cleaner syntax
  • Better readability
  • String interpolation
  • Support for expressions
  • Better integration with Text Blocks

Prerequisites

String Templates are available as a preview feature in Java 21.

To compile code using String Templates, enable preview features:


javac --enable-preview --release 21 Main.java

To run the program:


java --enable-preview Main

Syntax

Basic syntax:


String message = STR."Hello \{name}";

The placeholder:


\{expression}

is evaluated and inserted into the string.

Example 1: Simple Variable


String language = "Java";
String message = STR."Welcome to \{language}!";
System.out.println(message);

Output

Welcome to Java!

Example 2: Multiple Variables


String name = "Rahul";
int age = 22;
String details = STR."""
Name : \{name}
Age  : \{age}
""";
System.out.println(details);

Output

Name : Rahul
Age : 22

Notice how String Templates work naturally with Text Blocks.

Example 3: Expressions

You can place Java expressions inside placeholders.


int a = 20;
int b = 10;
String result = STR."Sum = \{a + b}";
System.out.println(result);

Output

Sum = 30

Example 4: Method Calls

Methods can also be evaluated.


String city = "delhi";
String message = STR."City: \{city.toUpperCase()}";
System.out.println(message);

Output

City: DELHI

Example 5: Object Properties


record Student(String name, int marks) {}
Student student = new Student("Ankit", 95);
String message = STR."""
Student Name : \{student.name()}
Marks        : \{student.marks()}
""";
System.out.println(message);

Output

Student Name : Ankit
Marks : 95

String Concatenation vs String Templates

Traditional Approach


String firstName = "John";
String lastName = "Doe";
String fullName =
       firstName + " " + lastName;

String Templates


String fullName =
       STR."\{firstName} \{lastName}";

The second version is shorter and easier to read.

Using Text Blocks with String Templates

One of the biggest advantages is combining Text Blocks and String Templates.


String name = "Rahul";
String course = "Java";
String email = STR."""
Dear \{name},
Welcome to the \{course} course
Happy Learning!
Regards,
ABC Institute
""";
System.out.println(email);

Output

Dear Rahul,
Welcome to the Java course.
Happy Learning!
Regards,
ABC Institute

This makes creating email templates much simpler.

Real-Life Example

Imagine an online shopping website.


String customer = "Amit";
String product = "Laptop";
double price = 65999.50;
String invoice = STR."""
Customer : \{customer}
Product  : \{product}
Price    : ₹\{price}
""";
System.out.println(invoice);

Output

Customer : Amit
Product : Laptop
Price : ₹65999.5

This is far more readable than multiple concatenations.

Working with Calculations

String Templates can evaluate expressions.


int quantity = 5;
int price = 100;
String bill = STR."Total = ₹\{quantity * price}";
System.out.println(bill);

Output

Total = ₹500

Built-in Template Processor

Java provides the STR template processor.

Example:


String language = "Java";
String message = STR."Learning \{language}";

The STR processor evaluates each embedded expression and produces the final string.

Future Java versions may introduce additional template processors for specialized use cases.

Advantages of String Templates

1. Better Readability

Code becomes much easier to understand.

2. Less Boilerplate

No repeated + operators.

3. Supports Expressions

Expressions can be evaluated directly inside placeholders.

4. Works with Text Blocks

Perfect for creating HTML, JSON, XML, SQL, and email templates.

5. Easier Maintenance

Updating templates requires fewer code changes.

6. Cleaner Code

Reduces visual clutter and improves developer productivity.

Common Use Cases

String Templates are useful for:

  • Email templates
  • HTML generation
  • JSON creation
  • XML documents
  • SQL query generation
  • Log messages
  • REST API responses
  • Configuration files
  • Reports
  • Notifications

String Templates vs String.format()

Feature String Templates String.format()
Readability Excellent Good
String interpolation Yes No
Supports expressions Yes Limited
Placeholder syntax \{} %s, %d, etc.
Type safety Better Moderate
Multi-line support Excellent Moderate
Works with Text Blocks Yes Yes

Best Practices

  • Use String Templates for dynamic strings.
  • Combine them with Text Blocks for multi-line content.
  • Keep embedded expressions simple and readable.
  • Avoid placing complex business logic inside placeholders.
  • Use meaningful variable names.
  • Remember that the feature is still in preview and may change in future Java releases.

Common Mistakes

1. Forgetting to Enable Preview Features

String Templates require preview features in Java 21.

Incorrect compilation:


javac Main.java

Correct compilation:


javac --enable-preview --release 21 Main.java

2. Using Complex Expressions

Avoid this:


String text = STR."\{calculateSalary(employee, department, taxRate)}";

Prefer calculating the value first:


double salary = calculateSalary(employee, department, taxRate);
String text = STR."\{salary}";

This improves readability.

3. Confusing Text Blocks with String Templates

A Text Block creates a multi-line string.

A String Template performs string interpolation.

They are different features but work well together.

4. Assuming the Feature is Final

As of Java 21, String Templates are a preview feature and may change in future Java versions. Avoid relying on them in production unless your project accepts preview features.

Conclusion

Java String Templates represent a significant step toward more expressive and developer-friendly string handling. By introducing built-in string interpolation, they eliminate much of the boilerplate associated with string concatenation and improve the readability of dynamic text generation. When combined with Text Blocks, they provide an elegant solution for creating formatted content such as HTML, JSON, SQL, XML, and email templates.

Although String Templates are still a preview feature in Java 21, they demonstrate the direction in which the Java language is evolving. Developers interested in modern Java features should explore String Templates, understand their capabilities and limitations, and monitor future Java releases for updates as the feature progresses toward standardization.

Related Java Tutorials