Java 21 String Templates
Java 21 introduced preview of String Templates which allow using string interpolation like Javascript Template Literals.
Enable Preview
To use String Templates, you need to enable the preview feature in gradle
tasks.withType(JavaCompile).configureEach {
options.compilerArgs += "--enable-preview"
}
tasks.withType(Test).configureEach {
jvmArgs += "--enable-preview"
}
tasks.withType(JavaExec).configureEach {
jvmArgs += "--enable-preview"
}
STR
- Use
\{varName}
to interpolate variable - Both single line string
"
and text block"""
are supported
import static java.lang.StringTemplate.STR;
class Main {
public static void main(String[] args) {
var name = "World";
System.out.println(STR."Hello, \{name}!");
System.out.println(STR."""
Hello!
This is a new \{name}!
""");
}
}