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 – 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 – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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 been removed in JDK 23, pending a redesign. Currently, this is only available if you’re using Java 21 or 22 with preview features enabled.

 

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 string 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.

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

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

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