DEV Community

Nermin Karapandzic
Nermin Karapandzic

Posted on

1

String Interpolation in Java, finally

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)"
Enter fullscreen mode Exit fullscreen mode

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}";
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

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>
        """;
Enter fullscreen mode Exit fullscreen mode

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).

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay