15. Introducing string templates
Until JDK 21, Java allows us to perform string composition for SQL, JSON, XML, and so on via different approaches, covered earlier in Problem 8. In that problem, you can see how to use text blocks and embedded expressions via simple concatenation, using the plus (+
) operator, StringBuilder.append()
, String.format()
, formatted()
, and so on. While using the plus (+
) operator and StringBuilder.append()
can be cumbersome and affect readability, the String.format()
and formatted()
may cause type mismatches. For instance, in the following example, it is quite easy to mess up the data types (LocalDate
, double
, and String
) and the format specifiers (%d
, %s
, and %.2f
):
LocalDate fiscalDate = LocalDate.now();
double value = 4552.2367;
String employeeCode = "RN4555";
String jsonBlock = """
{"sale": {
"id": 1,
"details": {
...