Lab 14: Text Blocks & String Processing

Objective

Master Java 21 text blocks for multiline strings, String.formatted(), stripIndent(), translateEscapes(), and advanced string processing: String.format with locale, String.join/Collectors.joining, StringBuilder tricks, regex with named groups, and a template engine using text blocks.

Background

Text blocks (JEP 378, Java 15+) are multiline string literals delimited by """. The compiler automatically strips common leading whitespace (stripIndent()). This enables embedding JSON, HTML, SQL, and YAML directly in code without escaping or concatenation — a major readability improvement.

Time

25 minutes

Prerequisites

  • Practitioner Lab 07 (Java 21 Features)

Tools

  • Docker: zchencow/innozverse-java:latest


Lab Instructions

Steps 1–8: Text block basics, stripIndent, HTML templates, JSON, SQL, formatted(), regex named groups, Capstone invoice generator

💡 Text blocks use """...""" and automatically strip leading whitespace. The JVM computes the "incidental whitespace" from the least-indented line and strips it uniformly. This means you can indent the content for readability without it appearing in the output. The closing """ on its own line controls this baseline — move it left to keep more indentation.

📸 Verified Output:


Summary

Feature
Syntax
Notes

Text block

"""..."""

Strips leading whitespace

Interpolation

str.formatted(args)

Like String.format on instance

stripIndent()

.stripIndent()

Manual strip incidental WS

Named group

(?<name>...) + .group("name")

Readable regex

Joining

Collectors.joining(sep, pre, suf)

Stream → delimited string

Further Reading

Last updated