Module java.base

Package java.lang.template

package java.lang.template
String templates and template processors provide a comprehensive system for combining literal text with the values from embedded expressions to produce a result. This result is often a String but is not limited to just Strings.

Java string templates look like string literals or text blocks except they contain one or more embedded expressions bracketed by \{ and }. An embedded expression is usually positioned in the string where the value of that embedded expression might expect to be inserted.

String interpolation is the most general use of string templates. The standard StringTemplate.STRPREVIEW template processor is statically imported into every Java compilation unit to facilitate the common use of string interpolation.

int x = 10;
int y = 20;
String s = STR."The result of adding \{x} and \{y} is \{x + y}.";
The value s in the above example will be "The result of adding 10 and 20 is 30.".

The expression STR."The result of adding \{x} and \{y} is \{x + y}." above is an example of a process template expression. A process template expression consists of a processor expression and a processor argument separated by a dot (period). A processor expression evaluates to an instance of type ValidatingProcessorPREVIEW. A processor argument is a string template that is represented by an instance of StringTemplatePREVIEW. The end result of the process template expression is the value that is produced by invoking the processor's ValidatingProcessor.process(StringTemplate)PREVIEW method of with the processor argument. Improper processor expressions or improper processor arguments result in compilation errors.

In the example above, STR is the processor that implements string interpolation with it ValidatingProcessor.process(StringTemplate)PREVIEW method.

The string template in the example, represented by a StringTemplatePREVIEW, contains the string fragments and embedded expression values expressed in "The result of adding \{x} and \{y} is \{x + y}.". In the example, the fragments are "The result of adding ", " and ", " is " and ".". The values are 10, 20 and 30, which are the result of evaluating x, y and x + y. See StringTemplatePREVIEW for examples and details.

String literals and text blocks can be used as proper processor arguments as well. This is automatically facilitated by the Java compiler converting the strings to StringTemplatePREVIEW using the StringTemplate.of(String)PREVIEW method.

Users can create their own template processors by implementing one of ValidatingProcessorPREVIEW, TemplateProcessorPREVIEW or StringProcessorPREVIEW interfaces. For more examples and details see StringTemplatePREVIEW and ValidatingProcessorPREVIEW.

See Java Language Specification:
15.8.6 Process Template Expressions
See Also: