What exactly is a String Template?
Template strings, often known as Java string templates, are a common feature found in many programming languages, including TypeScript template strings and Angular interpolation. Essentially, they allow us to insert variables into a string, and the variable values are determined at runtime. As a result, Java string templates generate varying output based on the specific values of the variables.
Table of Contents
Here are examples of Java string templates with different greetings and names:
// TypeScript
const nameTS = "John";
const messageTS = `Welcome ${nameTS}!`;
// Angular
const nameAngular = "Jane";
const messageAngular = `Welcome {{ ${nameAngular} }}!`;
// Python
namePython = "Alice"
messagePython = "Welcome {namePython}!"
// Java (using String.format)
String nameJava = "Bob";
String messageJava = String.format("Welcome %s", nameJava);
Each of the examples provided above will give you the same result when used with the same ‘name’ variable. JEP-430 is an effort to introduce template string support in the Java programming language, much like what you see here:
In Java 21, you can create a message using this syntax:
String name = "Bob";
String message = STR."Welcome \{name}!";
String Templates in the Java Language
The Old-Fashioned Way
String formatting in Java is not a new concept. Historically, programmers have employed various methods to create formatted strings, including string concatenation, StringBuilder, String.format(), and the MessageFormat class.
public class WelcomeMessage {
public static void main(String[] args) {
String message;
String name = "John";
// Concatenate a welcome message
message = "Welcome " + name + "!";
// Use String.format for formatting
message = String.format("Welcome %s!", name);
// Format using MessageFormat
message = new MessageFormat("Welcome {0}!").format(new Object[] { name });
// Construct efficiently with StringBuilder
message = new StringBuilder().append("Welcome ").append(name).append("!").toString();
// Display the final welcome message
System.out.println(message);
}
}
the output for each method will be the same, and it will display:
Welcome John!
Java String Templates in Java 21: Secure Interpolation
Java 21 has introduced template expressions, drawing inspiration from other programming languages. These expressions enable dynamic string interpolation during runtime. What sets Java’s approach apart is its focus on minimizing security risks, particularly when handling string values within SQL statements, XML nodes, and similar scenarios.
In terms of syntax, a template expression resembles a regular string literal with a specific prefix:
// Code Example
String message = STR."Greetings \{name}!";
In this context:
- STR represents the template processor.
- There is a dot operator (.) connecting the processor and the expression.
- The template string contains an embedded expression in the form of {name}.
- The outcome of the template processor, and consequently the result of evaluating the template expression, is often a String—although this isn’t always the case.
Template Processors in Java 21
In the world of Java, you’ll encounter three distinct template processors:
STR: This processor takes care of standard interpolation, making it a versatile choice for string manipulation.
FMT: Unlike its counterparts, FMT not only performs interpolation but also excels at interpreting format specifiers located to the left of embedded expressions. These format specifiers are well-documented within Java’s Formatter class.
RAW: RAW stands as a steadfast template processor, primarily generating unprocessed StringTemplate objects.
Here’s an example demonstrating how each of these processors can be utilized:
Here’s an example demonstrating how each of these processors can be utilized:
import static java.lang.StringTemplate.STR;
import static java.lang.StringTemplate.RAW;
public class TemplateProcessorTest {
public static void main(String[] args) {
String name = "JavaDZone";
System.out.println(STR."Welcome to \{name}");
System.out.println(RAW."Welcome to \{name}.");
}
}
To put it into action, execute the following command within your terminal or command prompt:
java --enable-preview --source 21 TemplateProcessorTest.java
Be sure to substitute “TemplateProcessorTest.java” with the actual name of your Java class.
Performing Arithmetic Operations within Expressions
In Java 21, you have the capability to carry out arithmetic operations within expressions, providing you with the means to compute values and showcase the results directly within the expression itself.
For instance, consider the following code snippet:
int operand1 = 10, operand2 = 20;
String resultMessage = STR."\{operand1} + \{operand2} = \{operand1 + operand2}"; // This will result in "10 + 20 = 30"
You can use multi-line expressions:
For the sake of improving code readability, you can split an embedded expression into multiple lines, emulating the style often seen in nested method calls resembling a builder pattern.
Here’s an example to illustrate this:
System.out.println(STR."The current date is: \{
DateTimeFormatter.ofPattern("yyyy-MM-dd")
.format(LocalDateTime.now())
}");
Exploring String Templates in Java 21
The following Java class, StringTemplateTest
, serves as an illustrative example of utilizing string templates with the STR
template processor. It demonstrates how to integrate string interpolation and various expressions within template strings. Each section is accompanied by a description to provide a clear understanding of the usage.
import static java.lang.StringTemplate.STR;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.LocalTime;
public class StringTemplateTest {
private static String name = "JavaDZone";
private String course = "Java21 Features";
private static int a = 100;
private static int b = 200;
public static void main(String[] args) {
// Using variable in template expression.
System.out.println(STR."Welcome to \{name}");
// Utilizing a method in the template expression.
System.out.println(STR."Welcome to \{getName()}");
StringTemplateTest st = new StringTemplateTest();
// Using non-static variable in the template expression.
System.out.println(STR."Welcome to \{st.course}");
// Performing arithmetic operations within the expression.
System.out.println(STR."\{a} + \{b} = \{a+b}");
// Displaying the current date using expression
System.out.println(STR."The current date is: \{DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now())}");
}
public static String getName() {
return name;
}
}
java --enable-preview --source 21 StringTemplateTest .java
make sure to change “StringTemplateTest.java” with the actual name of your Java class.
StringTemplateTest
class using the traditional java
or javac
methods, you may encounter the following error:
This error message indicates that string templates are considered a preview feature in Java, and they are not enabled by default. To enable and utilize string templates in your code, you should use the --enable-preview
–source 21 flag when running or compiling your Java program. This flag allows you to take advantage of string templates’ functionality.
In summary, this Java tutorial has explored the concept of string templates in Java. This feature was introduced in Java 21 as a preview, offering a fresh addition to the language’s capabilities. To stay updated on potential improvements and enhancements to this feature, be sure to keep an eye on the Java release notes. Enjoy your learning journey!