Text Blocks
Discover how to use Java text blocks to handle multiline strings such as JSON and SQL queries more cleanly and readably. Learn their syntax, how they intelligently manage whitespace and indentation, and how to insert dynamic content safely, improving code clarity and maintainability.
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 ...