In Java, we can create string templates containing embedded expressions (evaluated at runtime). Similar to other programming languages, Java template strings can include variables, methods or fields, computed at run time, to produce a formatted string as output.
String Templates (JEP-430) is a preview feature in Java 21.
1. What is a String Template?
Template string is a familiar feature that is present in most programming languages such as typescript template strings or angular interpolation. Basically, we embed the variables into a String and the values of the variables are resolved in runtime. Thus template strings produce different results for different values of the variables.
"Greetings {{ name }}!"; //Angular
`Greetings ${ name }!`; //Typescript
$"Greetings { name }!" //Visual basic
f"Greetings { name }!" //Python
All the above templates will produce the same result in runtime for the same value of the variable ‘name
‘. JEP-430 is a similar move to support template strings in Java.
String message = STR."Greetings \{ name }!"; //Java
2. String Templates in Java
2.1. Traditional Approaches
String formatting is not new in Java. Traditionally, programmers have been different ways to produce formatted strings such as string concatenation
, StringBuilder
, String.format()
and MessageFormat
class.
//concatenation
message = "Greetings " + name + "!";
//String.format()
message = String.format("Greetings %s!", name); //concatenation
//MessageFormat
message = new MessageFormat("Greetings {0}!").format(name);
//StringBuilder
message = new StringBuilder().append("Greetings ").append(name).append("!").toString();
All of the above approaches work but with drawbacks. Either they create code hard to read or they are just too verbose for a simple task.
2.2. Template Expressions
Taking inspiration from other languages, Java plans to support template expressions that can perform string interpolation in runtime. The only difference is that Java approach is less prone to introducing security vulnerabilities specially in string values used in SQL statements, XML nodes etc.
Syntactically, a template expression resembles a string literal with a prefix.
String message = STR."Greetings \{name}!";
In the above template expression:
- STR is the template processor.
- There is a dot operator (.) between the processor and the expression.
- Template string with embedded expression. The expression is in form of (
\{name}
).
The result of the template processor, and thus the result of evaluating the template expression, is often a String — though not always.
3. Template Processors
Currently, Java supports 3 template processors:
- STR: performs the standard interpolation.
- FMT: performs interpolation, as well as interprets the format specifiers (defined in a href=”https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Formatter.html”) which appear to the left of embedded expressions
- RAW: is a standard template processor that produces an unprocessed StringTemplate object.
String name = "Lokesh";
//STR
String message = STR."Greetings \{name}.";
//FMT
String message = STR."Greetings %-12s\{name}.";
//RAW
StringTemplate st = RAW."Greetings \{name}.";
String message = STR.process(st);
4. Features
4.1. Template Processor is Imported in Every Class
STR is a template processor and part of the language itself. It is a ‘public static final
‘ field that is automatically imported into every Java source file so we can it directly. There is no need to import it.
4.2. Expressions support Variables, Member Fields and Methods
We can use local variables, static/non-static fields and even methods as the embedded expressions. Their values are computed at runtime.
//variable
message = STR."Greetings \{name}!";
//method
message = STR."Greetings \{getName()}!";
//field
message = STR."Greetings \{this.name}!";
4.3. Arithmetic is supported inside expressions
We can perform calculations and print the result in the same expression.
int x = 10, y = 20;
String s = STR."\{x} + \{y} = \{x + y}"; //"10 + 20 = 30"
4.4. Double quotes are supported without escape
As opposed to any other feature in Java, we can include double quotes without escaping in template strings. It provides very much-needed readability in Java strings.
String name = "Alex";
String msg = STR."The first name is \{filePath} exists in the "SQL Database".";
//produces - The first name is Alex exists in the "SQL Database".
4.5. Multi-line expressions are allowed
To improve readability, we can break an embedded expression into multiple lines. It is very much like nested method calls in builder pattern style code.
String time = STR."The current time is \{
//sample comment - current time in HH:mm:ss
DateTimeFormatter
.ofPattern("HH:mm:ss")
.format(LocalTime.now())
}.";
5. Conclusion
This Java tutorial discusses string templates in Java which is a new addition to the language in Java 21 as a preview feature. Keep watching for Java release notes for more changes to this feature.
Happy Learning !!