Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

In this tutorial, we’ll talk about Java’s answer to String interpolation – String templates. This pre-release preview feature was introduced as part of Java 21 with JEP 430.

2. String Composition in Java

We use Strings to represent sequences of numbers, letters, and symbols to represent text in code. Strings are ubiquitous in programming, and we often need to compose strings to use in code. There are several ways to do that, and each technique has its downsides.

2.1. String Concatenation

String concatenation is the most basic action we use to build strings. We take strings literals and expressions and then use the + symbol to compose them together:

String composeUsingPlus(String feelsLike, String temperature, String unit){
    return "Today's weather is " + feelsLike + 
      ", with a temperature of " + temperature + " degrees " + unit;
}

This code achieves the desired functionality but is hard to read, especially with all the plus symbols, and also difficult to maintain and change.

2.2. StringBuffer or StringBuilder

We can use utility classes Java provides, such as the StringBuilder and StringBuffer classes. These classes provide us with the append() library function to compose strings, thereby removing the usage of + in string composition:

String composeUsingStringBuilder(String feelsLike, String temperature, String unit) {
    return new StringBuilder()
      .append("Today's weather is ")
      .append(feelsLike)
      .append(", with a temperature of ")
      .append(temperature)
      .append(" degrees ")
      .append(unit)
      .toString();
}

StringBuilder and StringBuffer classes provide efficient String manipulation and composition techniques while reducing memory overheads. However, they follow the Builder design pattern and hence become quite verbose.

2.3. String Formatter

Java provides us with the capability to separate the static part of the String and the parameters, such as the temperature and the unit with the String.format() or the formatted() methods:

String composeUsingFormatters(String feelsLike, String temperature, String unit) {
    return String.format("Today's weather is %s, with a temperature of %s degrees %s", 
      feelsLike, temperature, unit);
}

The base template string remains static. However, the order and the number of arguments passed here are crucial for the correctness of its response.

2.4. MessageFormat Class

Java provides a MessageFormat class of the Java.text package that helps in the composition of text messages with placeholders for dynamic data. Localisation and Internationalisation heavily use this. We can use MessageFormat.format() in plain String composition:

String composeUsingMessageFormatter(String feelsLike, String temperature, String unit) {
    return MessageFormat.format("Today''s weather is {0}, with a temperature of {1} degrees {2}",
      feelsLike, temperature, unit);
}

This also shares a similar downside as that of the above. Additionally, the syntax structure differs from how we write and use strings in code.

3. Introduction to String Templates

As we saw, all the String composition techniques mentioned above come with their shortcoming. Let’s see how String templates can help with those.

3.1. Goals

String templates are introduced to the Java programming ecosystem with the following goals in mind:

  • Simplify the process of expressing Strings with values that can be compiled at run time
  • Enhanced readability of String compositions, overcome the verbosity associated with StringBuilder and StringBuffer classes
  • Overcome the security issues of the String interpolation techniques that other programming languages allow, trading off a small amount of inconvenience
  • Allow Java libraries to define custom formatting syntax of the resulting String literal

3.2. Template Expressions

The most important concept of String templates revolves around template expressions, a new kind of programmable expressions in Java. Programmable template expressions can perform interpolation but also provide us with the flexibility to compose the Strings safely and efficiently.

Template expressions can turn structured text into any object, not just limited to Strings.

There are three components to a template expression:

  • A processor
  • A template which contains the data with the embedded expressions
  • A dot (.) character

4. Template Processors

A template processor is responsible for evaluating the embedded expression (the template) and combines it with the String literal at runtime to produce the final String. Java provides the ability to use an inbuilt template processor, provided by Java, or switch it with a custom processor of our own.

This is a preview feature in Java 21; hence, we would have to enable preview mode.

4.1. STR Template Processor

Java provides some out-of-the-box template processors. The STR Template Processor performs string interpolation by iteratively replacing each embedded expression of the provided template with the stringified value of that expression. We will apply the STR processor String template in our previous example here:

String interpolationUsingSTRProcessor(String feelsLike, String temperature, String unit) {
    return STR
      . "Today's weather is \{ feelsLike }, with a temperature of \{ temperature } degrees \{ unit }" ;
}

STR is a public static final field and is automatically imported into every Java compilation unit.

We can extend the above implementation not just to single-line Strings but to multiline expressions as well. For multiline text blocks, we surround the text block with “””. Let’s take the example of interpolating a String that represents a JSON:

String interpolationOfJSONBlock(String feelsLike, String temperature, String unit) {
    return STR
      . """
      {
        "feelsLike": "\{ feelsLike }",
        "temperature": "\{ temperature }",
        "unit": "\{ unit }"
      }
      """ ;
}

We can also inject expressions inline, which will compile at runtime:

String interpolationWithExpressions() {
    return STR
      . "Today's weather is \{ getFeelsLike() }, with a temperature of \{ getTemperature() } degrees \{ getUnit() }";
}

4.2. FMT Template Processor

Another Java-provided processor is the FMT Template Processor. It adds the support of understanding formatters that are provided to the processor and format the data according to the formatting style provided.

The supplied formatter should be similar to java.util.Formatter:

String interpolationOfJSONBlockWithFMT(String feelsLike, float temperature, String unit) {
    return FMT
      . """
      {
        "feelsLike": "%1s\{ feelsLike }",
        "temperature": "%2.2f\{ temperature }",
        "unit": "%1s\{ unit }"
      }
      """ ;
}

Here, we use %s and %f to format the string and the temperature in a specific format.

4.3. Evaluation of a Template Expression

There are a few steps involved in the evaluation of a template expression in the line:

STR
  . "Today's weather is \{ feelsLike }, with a temperature of \{ temperature } degrees \{ unit }" ;

The above is a shorthand for several steps that we’ll see.

First, an instance of a template processor, StringTemplate.Processor<R, E> is obtained by evaluating the left of the dot. In our case, it is the STR template processor.

Next, we obtain an instance of a template, StringTemplate, by evaluating to the right of the dot:

StringTemplate str = RAW
  . "Today's weather is \{ getFeelsLike() }, with a temperature of \{ getTemperature() } degrees \{ getUnit() }" ;

RAW is the standard template processor that produces an unprocessed StringTemplate type object.

Finally, we pass the StringTemplate str instance to the process() method of the processor(which in our case is STR):

return STR.process(str);

5. String Interpolation and String Templates

We have now seen examples of using String templates as a string composition technique, and we can see that it is very similar to String interpolation. However, String templates provide the safety that String interpolation on other platforms generally does not guarantee.

Template expressions are designed intentionally so that it is impossible to interpolate a String literal or text block containing an embedded expression to an output String directly. The processor’s presence ensures that dangerous or incorrect Strings do not propagate through the code. It is the processor’s responsibility to validate that the interpolation is safe and correct.

The absence of any template processor will generate a compile-time error. Also, if the processor fails to interpolate, it can generate an Exception.

Java decides to treat “<some text>” as a StringLiteral or a StringTemplate based on the presence of the embedded expressions. The same is followed for “””<some text>””” to distinguish between TextBlock and TextBlockTemplate. This distinction is important to Java because even though, in both cases, it is wrapped between double quotes(“”), a String template is of type java.lang.StringTemplate, an interface, and not the java.lang.String.

6. Conclusion

In this article, we discussed several String composition techniques and understood the idea behind String interpolation. We also looked at how Java is introducing the idea of String interpolation with the help of String templates. Finally, we looked at how String templates are better and safer to use than the general String interpolation.

As usual, the code is available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
3 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.