Sitemap

Feature of Java 22 — String Templating (Learn in 2 minutes)

2 min readJul 11, 2024

--

Although I personally see it as a feature I will never need to use, it is good to know that it is available.

Press enter or click to view image in full size
Photo by DESIGNECOLOGIST on Unsplash

In the endeavor to make Java more modern, we have a new feature — *drum roll* — String Templating!! What is it and why do we need it? Great Question. Let’s get into it.

Get Full Stack Developer’s stories in your inbox

Join Medium for free to get updates from this writer.

Remember writing code like this —

//Variables to be printed
String name = "Alice";
int age = 30;

//String Concatenation method
String message = "Hello, " + name + ". You are " + age + " years old.";

//String Format method
String message = String.format("Hello, %s. You are %d years old.", name, age);


System.out.println(message);

I don’t but let’s assume I had a need to print a String like this. Now as it gets more complex, and number of lines of String increases, the worse it looks, and becomes hard to maintain.

With String Templating you are allowed to embed expressions or variables within string literals. This makes it easier to construct dynamic strings by directly including variable values or results of expressions within the string.

// Using string templating

String name = "Alice";
int age = 30;

String message = STR."Hello, \{name}. You are \{age} years old.";

System.out.println(message);

So basically, Java’s introduction of string templating aims to enhance code readability, maintainability, and flexibility, while reducing boilerplate code and aligning with modern programming practices. This feature addresses common pain points and improves the overall developer experience when working with dynamic strings in Java.

Some more uses of String Template in complex scenarios —

String message = STR."Hello, \{user.getFullName()}. Your balance is
\{account.getBalance()} dollars.";


String sqlQuery = STR."
SELECT *
FROM \{tableName}
WHERE \{columnName} > \{ageThreshold}";


String logMessage = STR."""
[\{timestamp.format(DateTimeFormatter.ofPattern
("yyyy-MM-dd HH:mm:ss"))}]
User ID: \{userId}
Action: \{action}
Status: \{status}
IP Address: \{ip}
Session ID: \{sessionId}
""";

Happy Coding!

--

--

Full Stack Developer
Full Stack Developer

Written by Full Stack Developer

This blog is curated just for you, if you are a Developer planning to appear for interviews OR looking out for new & interesting things happening in Java Space.