Numerous noteworthy enhancements were introduced in the versions spanning from 19 to 21, encompassing Virtual threads, structured concurrency, scoped values, foreign function, and memory API. Despite these significant strides, the spotlight often bypassed the smaller yet equally crucial changes.
In this brief discourse, I'd like to highlight one of my favorites – the introduction of a user-friendly string interpolation feature known as string templates.
Up until now, the Java ecosystem had traversed various methods for string composition:
- String concatenation
- StringBuffer or StringBuilder
- String format method
- MessageFormat class
or perhaps, the favored choice for many: Messages.format
from the Apache Commons library.
However, none of these methods truly paralleled the ease of real string interpolation, a feature commonplace in most other programming languages.
C# $"{x} plus {y} equals {x + y}"
Visual Basic $"{x} plus {y} equals {x + y}"
Python f"{x} plus {y} equals {x + y}"
Scala s"$x plus $y equals ${x + y}"
Groovy "$x plus $y equals ${x + y}"
Kotlin "$x plus $y equals ${x + y}"
JavaScript `${x} plus ${y} equals ${x + y}`
Ruby "#{x} plus #{y} equals #{x + y}"
Swift "\(x) plus \(y) equals \(x + y)"
but now we can add Java to the list
String s = STR."\{x} + \{y} = \{x + y}";
STR is a template processor included in the Java platform.
It performs string interpolation by replacing each embedded expression in the template with the (stringified) value of that expression. The result of evaluating a template expression which uses STR is a String; e.g., "My name is Joan".
STR is a public static final field that is automatically imported into every Java source file.
Here are some examples of using STR template processor:
String firstName = "Bill";
String lastName = "Duck";
String fullName = STR."\{firstName} \{lastName}";
Output: "Bill Duck"
String filePath = "tmp.dat";
File file = new File(filePath);
String old = "The file " + filePath + " " + (file.exists() ? "does" : "does not") + " exist";
String msg = STR."The file \{filePath} \{file.exists() ? "does" : "does not"} exist";
Output: "The file tmp.dat does exist" or "The file tmp.dat does not exist"
We can also use it with multi-lines, similar to text blocks:
String title = "My Web Page";
String text = "Hello, world";
String html = STR."""
<html>
<head>
<title>\{title}</title>
</head>
<body>
<p>\{text}</p>
</body>
</html>
""";
There is a way for us to define our own template processors, for example to safely build sql queries using prepared statements, but I'll leave this for you to research on your own.
You can read about that and many other details in the official (JEP 459).
Top comments (0)