Overview of String Templates in Java 21
String Templates are a new feature introduced in Java 21 that allows developers to create strings in a
more flexible and readable manner. This feature enhances the way you construct strings, making it
easier to embed variables and expressions directly into string literals. String Templates provide a
cleaner syntax and improve code readability, especially when dealing with complex string
manipulations.
Key Features of String Templates
Simplified Syntax: Using curly braces {} to embed expressions directly into the string.
Type Safety: The template engine ensures that the expressions are evaluated and inserted
correctly.
Enhanced Readability: Reduces boilerplate code and makes it clear which parts of the string
are dynamic.
So this is how we achieve multi lining In java
If want to write in the same in multiple lines: we have :
After java 15 we ca write it like this: that is a text block
Now the next update is String Template:
If we want to add two values:
Previously we are doing it like this :
Now by using string templelate:
You can see that the string template are a preview feature which is disabled In the beta version.
So to remove this error
import java.util.List;
import static java.lang.StringTemplate.STR;
public class TemplateExample {
public static void main(String[] args) {
int a=8;
int b=9;
String result = STR."\{a}+\{b} = \{a+b}";
System.out.println(result);
String name = "Alice";
int age = 30;
String greeting = STR."Hello, \{name}! You are \{age} years old.";
System.out.println(greeting); // Output: Hello, Alice! You are 30 years old.
}
}
run with command line like this:
javac --enable-preview --release 21 TemplateExample.java
java --enable-preview TemplateExample
Conclusion
String Templates in Java 21 offer a powerful and efficient way to handle string interpolation. They
enhance code clarity, reduce boilerplate, and provide a more intuitive syntax for developers. As you
integrate this feature into your applications, you'll find that it streamlines string handling, making
your code cleaner and easier to maintain.