String Templates

Why string templates are needed

In programs, we often create strings with embedded values of expressions. Concatenating values to create strings using the + operator makes the code verbose and hard to maintain. String templates solve that problem by providing an elegant solution.

How to use string templates

Within a double-quoted string, the $ symbol can prefix any variable to turn that into an expression. If the expression is more complex than a simple variable, then wrap the expression with ${}.

A $ symbol that’s not followed by a variable name or expression is treated as a literal. You may also escape the $ symbol with a backslash to use it as a literal.

Here’s an example with a string template. Also, it contains a plain string with embedded $ symbols that are used as literals.

Get hands-on with 1400+ tech skills courses.