Template Expressions: A New Expression Type in Java — Java 21

Bayram EKER
4 min readOct 22, 2023

--

Introduction: In the Java programming language, template expressions introduce a new type of expression. In this article, we will explore what template expressions are, how they are used, and the advantages they offer with code examples.

Definition of Template Expressions

Template Expressions are a new type of expression in the Java language. They provide a programmable structure to concatenate strings while assisting developers in combining strings safely and efficiently. Template expressions are not limited to just string concatenation; they can transform structured text into any object according to domain-specific rules.

Template Expression Syntax

A template expression looks similar to a string enclosed with a prefix. The following code example illustrates a template expression in Java:

String name = "Joan";
String info = STR."My name is \{name}";
assert info.equals("My name is Joan"); // true

In this example, a template expression is used with a prefix “STR.”. A template expression consists of:

  1. A template processor (e.g., STR)
  2. A period character (U+002E), similar to other expression types
  3. A text with embedded expressions (“My name is {name}”)

When a template expression is evaluated at runtime, it combines the values of embedded expressions in the text to produce a result. The result of the template processor and, therefore, the evaluation of the template expression is typically a string, but it doesn’t have to be.

STR Template Processor

STR is a template processor defined in the Java platform. STR performs string interpolation, replacing embedded expressions in the text with the value of the expression. When you evaluate a template expression using the STR processor, the result is a string, such as “My name is Joan.”

Examples of Using Template Expressions

Here are more examples using the STR template processor:

Example 1: Embedded Expressions Can Be Strings

String firstName = "Bill";
String lastName = "Duck";
String fullName = STR."\{firstName} \{lastName}";
// fullName: "Bill Duck"
String sortName = STR."\{lastName}, \{firstName}";
// sortName: "Duck, Bill"

Example 2: Embedded Expressions Can Perform Arithmetic Operations

int x = 10, y = 20;
String s = STR."\{x} + \{y} = \{x + y}";
// s: "10 + 20 = 30"

Example 3: Embedded Expressions Can Invoke Methods and Access Fields

String s = STR."You have a \{getOfferType()} waiting for you!";
// s: "You have a gift waiting for you!"
String t = STR."Access at \{req.date} \{req.time} from \{req.ipAddress}";
// t: "Access at 2022-03-25 15:34 from 8.8.8.8"

Making Refactoring Easier with Double Quotes

In template expressions, you can use double quotes without escaping embedded expressions with “. This allows embedded expressions to appear within the template expression as they do outside, making the transition from string concatenation (+) to template expressions easier.

For example:

String filePath = "tmp.dat";
File file = new File(filePath);
String old = "The file " + filePath + " " + (file.exists() ? "does" : "does not") + " exist";
String msg = STR."The file \{filePath} \{file.exists() ? "does" : "does not"} exist";

Using Embedded Expressions Across Multiple Lines

Allowing embedded expressions to span multiple lines in the source file means that the value of the embedded expression is concatenated with the result in the string without adding newlines.

For example:

String time = STR."The time is \{
// The java.time.format package is very useful
DateTimeFormatter
.ofPattern("HH:mm:ss")
.format(LocalTime.now())
} right now";
// time: "The time is 12:34:56 right now"

Using Multiple Embedded Expressions

There is no limitation on using multiple embedded expressions within a string template expression. Embedded expressions are evaluated from left to right, just like in method invocation expressions.

For example:

int index = 0;
String data = STR."\{index++}, \{index++}, \{index++}, \{index++}";
// data: "0, 1, 2, 3"

Any Java expression can be embedded. However, using complex expressions where simplicity is required is not recommended while maintaining type safety in template expressions.

Template Processor Options: STR and FMT

The fundamental template processors in Java are STR and FMT. While STR performs string interpolation, FMT extends this to string interpolation and custom formatting options.

FMT Template Processor

The FMT template processor supports string interpolation and custom formatting options, following the rules of java.util.Formatter.

For example:

String formatted = FMT."The price is: \{price, number, currency}";
// formatted: "The price is: $50.00"

Security Assurance

Template expressions in Java prioritize security. A template expression is a shorthand for calling the process method of a template processor. This design prevents incorrect string interpolation from propagating through the program and ensures accurate and secure interpolation.

Template Processor API

Developers can create their own template processors. Custom template processors can return objects of any type and even throw checked exceptions. Implementing the StringTemplate.Processor interface allows developers to handle custom use cases.

Creating and Executing Secure Database Queries

Template expressions simplify the secure creation and execution of database queries. An example QueryBuilder demonstrates the use of a template processor, preventing SQL injection vulnerabilities.

Simplifying Localization

Template processors make it easier to handle localization tasks by mapping templates to resource bundles. This approach enables developers to create template processors that automatically fetch localized strings from resource bundles, making localization work easier and more manageable.

In conclusion, template expressions in Java provide a powerful tool for handling string interpolation and text generation processes safely and efficiently. Template processors like STR and FMT enable developers to easily create dynamic, localized, and secure strings. The ability to create custom template processors adds flexibility and extensibility to this feature, making it a significant addition to Java’s toolbox for working with text and data.

Happy Coding! 🚀

Thank you for taking the time to read my thoughts and musings here on Medium! If you found any value or resonance in what you’ve read, please consider giving this article some claps👏. It means a lot to me and encourages me to keep sharing with this wonderful community. Stay tuned for more, and don’t forget to spread love and kindness wherever you go. Until next time! ✨

--

--

Responses (1)