0
0
JavaConceptBeginner · 3 min read

What is String Templates in Java: Simple Explanation and Example

In Java, string templates allow you to embed variables and expressions directly inside string literals for easier and cleaner string creation. This feature is supported by Text Blocks and the newer String Templates API introduced in preview, making string formatting simpler and more readable.
⚙️

How It Works

String templates in Java let you write strings that include placeholders for variables or expressions. Instead of building strings by joining parts manually, you write a template with special markers that get replaced by actual values when the program runs.

Think of it like filling out a form: the template is the form with blank spaces, and the variables are the answers you fill in. Java then combines them into a complete string automatically.

This makes your code cleaner and easier to read, especially when creating complex strings like messages, SQL queries, or HTML content.

💻

Example

This example shows how to use the preview String Templates API in Java 21 to embed variables inside a string template.

java
import java.lang.StringTemplates;

public class StringTemplateExample {
    public static void main(String[] args) {
        String name = "Alice";
        int age = 30;

        String message = STR."Hello, \{name}! You are \{age} years old.";

        System.out.println(message);
    }
}
Output
Hello, Alice! You are 30 years old.
🎯

When to Use

Use string templates when you want to create strings that include dynamic data in a clear and concise way. They are especially helpful for:

  • Building user messages or logs that include variable values.
  • Generating SQL queries or HTML with embedded data.
  • Reducing errors and improving readability compared to manual string concatenation.

Since the String Templates API is a preview feature in Java 21, it is best for experimental or new projects where you want to try modern, cleaner string formatting.

Key Points

  • String templates embed variables directly inside string literals.
  • They improve code readability and reduce manual concatenation.
  • Java 21 introduces a preview String Templates API for this feature.
  • Use them for dynamic messages, queries, and formatted text.

Key Takeaways

String templates let you embed variables inside strings for cleaner code.
Java 21 offers a preview String Templates API to simplify string formatting.
They reduce errors and improve readability compared to concatenation.
Ideal for dynamic messages, queries, and formatted output.
Currently a preview feature, so use in experimental or new projects.