Java 21 String Templates

Since Java 21, we can create string templates containing the embedded expressions (evaluated at runtime). Similar to other programming languages, Java template strings can include variables, methods or fields, computed at run time, to produce a formatted string as output.

String Templates (JEP-430) is a preview feature in Java 21.

1. What is a String Template?

Template string is a familiar feature that is present in most programming languages such as typescript template strings or angular interpolation. Basically, we embed the variables into a String and the values of the variables are resolved in runtime. Thus template strings produce different results for different values of the variables.

"Greetings {{ name }}!";  //Angular
`Greetings ${ name }!`;   //Typescript
$"Greetings { name }!"    //Visual basic
f"Greetings { name }!"    //Python

All the above templates will produce the same result in runtime for the same value of the variable ‘name‘. JEP-430 is a similar move to support template strings in Java.

String name= "Alex";
String message = STR."Greetings \{ name }!";
System.out.println(message);

The program output:

Greetings Alex!

2. The Motivation behind String Templates

To better understand the String templates, we must first understand how we build a string containing runtime values. Thenwe can compare the old approach to new feature to appreciate its usefulness.

2.1. Traditional Approaches for String Formatting

String formatting is not new in Java. Traditionally, programmers have been different ways to produce formatted strings such as:

  • String concatenation
  • StringBuilder class
  • String.format()
  • MessageFormat class
String name= "Alex";

//concatenation
message = "Greetings " + name + "!";	

//String.format()
message = String.format("Greetings %s!", name);	//concatenation

//MessageFormat
message = new MessageFormat("Greetings {0}!").format(name);

//StringBuilder
message = new StringBuilder().append("Greetings ").append(name).append("!").toString();

All of the above approaches work but with drawbacks. Either they create code hard to read or they are just too verbose for a simple task.

2.2. Template Expressions are a Cleaner Approach

Taking inspiration from other languages, Java plans to support template expressions that can perform string interpolation in runtime. The only difference is that Java approach is less prone to introducing security vulnerabilities specially in string values used in SQL statements, XML nodes etc.

Syntactically, a template expression resembles a string literal with a prefix denoting the template processor.

String message = STR."Greetings \{name}!";

In the above template expression:

  • STR is the template processor.
  • There is a dot operator (.) between the processor and the expression.
  • Template string with embedded expression. The expression is in form of (\{name}).

The result of the template processor, and thus the result of evaluating the template expression, is often a String — though not always.

3. Available Template Processors for Strings

Currently, Java supports 3 template processors:

  • STR: performs the standard interpolation.
  • FMT: performs interpolation, as well as interprets the format specifiers which appear to the left of embedded expressions
  • RAW: is a standard template processor that produces an unprocessed StringTemplate object.
String name = "Lokesh";	

//STR
String message = STR."Greetings \{name}.";

//FMT
String message = STR."Greetings %-12s\{name}.";

//RAW
StringTemplate st = RAW."Greetings \{name}.";
String message = STR.process(st);

Somehow, FMT and RAW seems not working in the latest JDK version as of today. May be a later JDK update will fix this issue.

4. Main Highlights of String Template Processing

Now let us go through some important concepts that we must know when writing the new template strings.

4.1. Template Processors are Imported in Every Class

A template processor is part of the language itself. It is a ‘public static final‘ field that is automatically imported into every Java source file so we can it directly.

There is no need to import a template processor explicitly.

4.2. Template Expressions support Variables, Member Fields and Methods

We can use local variables, static/non-static fields and even methods as the embedded expressions. Their values are computed at runtime.

//variable
message = STR."Greetings \{name}!";

//method
message = STR."Greetings \{getName()}!";

//field
message = STR."Greetings \{this.name}!";

4.3. Arithmetic is Supported in the Expressions

We can perform calculations and print the result in the same expression.

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

4.4. Double Quotes are Supported without Escape

As opposed to any other feature in Java, we can include double quotes without escaping in template strings. It provides very much-needed readability in Java strings.

Boolean result = true;  //Can be false also

String name = "Alex";
String msg = STR."The record for \{name} \{result ? "does" : "does not"} exist in the database.";

System.out.println(msg);  //Prints: The record for Alex does exist in the database. 

4.5. Multi-line Expressions are Allowed

To improve readability, we can break an embedded expression into multiple lines. It is very much like nested method calls in builder pattern style code.

String time = STR."The current time is \{
    //sample comment - current time in HH:mm:ss
    DateTimeFormatter
      .ofPattern("HH:mm:ss")
      .format(LocalTime.now())
	}.";

5. Conclusion

This Java tutorial discusses string templates in Java which is a new addition to the language in Java 21 as a preview feature. Keep watching for Java release notes for more changes to this feature.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode