Java 21 — String Templates

Hemant
2 min readSep 21, 2023

--

String Templatesis new feature introduced in Java 21. String templates complement Java’s existing string literals.

In this post we will understand what are String Templates and how can we use them.

OpenJDK 21

String Templates provides a template-based mechanism for composing strings. Which improves the readability and reliability of these functions.

Strings in Java are default to each function in Java. Many times we have a requirement where we need to compose messages i.e. Email Body or data structures i.e. JSON, XML

To achieve this we have to write a lot of verbose and unreliable code. String Templates provides a readable and reliable way to write code for these scenarios.

We will understand this with sample code.

I am adding JDK 21 related resources and sample codes in this git repo.

Samples for code used below is also included in this git repo.

# Example 1 —Create JSON Object Using Function

Requirement — Write a function to Create a JSON Object of three fields — first_name, last_name & country

Before JDK 21

Implementation using String.format method (there are other ways too)

public static String prepareJsonBeforeJava21(String firstName, String lastName, String country){
return String.format("{\n\t\"first_name\": \"%s\",\n\t\"last_name\": \"%s\",\n\t\"country\": \"%s\"\n}", firstName, lastName, country);
}

After JDK 21

Implementation using String Templates

public static String prepareJson(String firstName, String lastName, String country){
return
"""
{
"first_name": "%s",
"last_name": "%s",
"country": "%s"
}
""".formatted(firstName, lastName, country);
}

# Example 2— Prepare Email Body Function

Requirement — Write a function to prepare an email body to welcome user based on user name

Before JDK 21

Implementation using StringBuilder class (there are other ways too)

public static String prepareEmailBodyBeforeJDK21(String name){
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("<html>\n <body>");
stringBuilder.append(String.format("<p> Welcome %s to our planet.</p> \n", name));
stringBuilder.append("</body>\n</html>");
return stringBuilder.toString();
}

After JDK 21

Implementation using String Templates

public static String prepareEmailBody(String name){
return
"""
<html>
<body>
<p> Welcome %s to our planet.</p>
</body>
</html>
""".formatted(name);
}

Using examples we saw how String Templates increased code readability and reliability where we have to create strings based on business logic.

Happy Learning

--

--

Hemant

Lead Software Engineer @JPMorgan & Chase. Writes about Java, AWS and System Design