Text Blocks
Explore how Java text blocks streamline handling multi-line strings by preserving formatting and reducing escape characters. Understand their syntax, whitespace rules, escaping techniques, and how to interpolate variables cleanly, making it easier to work with JSON, XML, and SQL in your code.
For years, working with multi-line text in Java was a messy experience. If we wanted to store a snippet of JSON or a SQL query in a variable, we had to concatenate multiple strings with plus signs and manually insert newline characters (\n). Worse, if the text contained double quotes, we had to “escape” every single one of them with a backslash (\"). The result was code that was hard to read and even harder to edit.
Text blocks were finalized in Java 15 to solve this specific problem. Text blocks treat multi-line strings as first-class citizens, allowing us to paste formatted text directly into our code while preserving its structure and readability.
The syntax of text blocks
A text block is defined by three double quotes ("""), followed immediately by a line terminator. The content of the string begins on the next line and ends when the closing triple quotes appear.
The most critical rule to remember is that ...