String Templates
NOTE: This is a preview feature NOT enabled by-default in JDK-21.
String Templates are introduced as per java specification JPE-430.
They provide a way to introduce variables into strings which are resolved during runtime.
public class StringTemplate {
private static String name = "T2P";
private static String message = STR."Greetings from \{name}!";
public static void main(String[] args) {
System.out.println(message); //Expected Output: Greetings from T2P!
}
}
Lets say we run this program via command prompt
java StringTemplate.java
This code will not compile and we’ll get below errors
StringTemplate.java:4: error: string templates are a preview feature and are disabled by default.
private static String message = STR."Greetings from \{name}!";
^
(use --enable-preview to enable string templates)
1 error
error: compilation failed
So in order to resolve it, we need to enable the preview feature using --enable-preview
for jdk 21 using --source 21
java --enable-preview --source 21 StringTemplate.java
Now we can see the program compiles correctly and produces the below output
Note: StringTemplate.java uses preview features of Java SE 21.
Note: Recompile with -Xlint:preview for details.
Greetings from T2P!
Finally we got our code running 🤩.
Few more points on String Templates
-
STR
template processor is the part of the language and is automatically included in every class. - Not only local variables but methods and instance variables are also supported.
String message = STR."Greetings from \{name}!"; //local variable String message = STR."Greetings from \{getName()}!"; //method String message = STR."Greetings from \{this.name}!"; //instance variable
- Mathematical Expressions too.
int a = 10, b = 30; String result = STR."\{a+b}"; //40
- Double quotes need not to be escaped in String Templates
boolean test = true; String msg = STR."The result is \{ test? "true" : "false" }."; //The result is true.
- Multi-line expressions are allowed too.
import java.time.LocalDateTime; String currentDateTime = STR."Current Date and Time is: \{ LocalDateTime.now() }"; //Current Date and Time is: 2023-10-07T08:55:36.874386100