Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat= Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

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

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – All Access – NPI EA (cat= Spring)
announcement - icon

All Access is finally out, with all of my Spring courses. Learn JUnit is out as well, and Learn Maven is coming fast. And, of course, quite a bit more affordable. Finally.

>> GET THE COURSE
Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

End-to-end testing is a very useful method to make sure that your application works as intended. This highlights issues in the overall functionality of the software, that the unit and integration test stages may miss.

Playwright is an easy-to-use, but powerful tool that automates end-to-end testing, and supports all modern browsers and platforms.

When coupled with LambdaTest (an AI-powered cloud-based test execution platform) it can be further scaled to run the Playwright scripts in parallel across 3000+ browser and device combinations:

>> Automated End-to-End Testing With Playwright

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

1. Introduction

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

However, the feature has now been removed in JDK 23, pending a re-design.

 

2. String Composition in Java

We use Strings to represent sequences of numbers, letters, and symbols as 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 this, 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, 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 also use utility classes provided by Java, 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 therefore 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 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 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 technique shares a similar downside to that of the above option. Furthermore, 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 shortcomings. Now 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 expression 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, they’re not just limited to Strings.

There are three components to a template expression:

  • a processor
  • a template that 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 combining 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 to switch it with a custom processor of our own.

This is a preview feature in Java 21; therefore, we’d 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’ll 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 multi-line expressions as well. For multi-line 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 the formatters that are provided to the processor, which 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’s 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’ve now seen examples of using String templates as a string composition technique, and we can see that it’s very similar to String interpolation. However, String templates provide the safety that String interpolation on other platforms generally don’t guarantee.

Template expressions are designed intentionally so that it’s 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 don’t propagate through the code. It’s 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 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’s 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 examined 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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

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

>> CHECK OUT THE COURSE

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (All)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)
3 Comments
Oldest
Newest
Inline Feedbacks
View all comments