Quiz: Text Blocks in Java

Total: 8 questions

1. 

What is a text block in Java, and which Java version supports it?

A text block is a multi-line string literal enclosed in triple quotes """. Inside it you can write line breaks and quotes without escaping, and the compiler removes the indentation that comes from code formatting. The result is an ordinary String; there is no new type.

String sql = """
        SELECT id, name
        FROM users
        WHERE active = 1
        """;

Text blocks appeared as a preview in Java 13 (JEP 355) and became a permanent part of the language in Java 15 (JEP 378); Java 8 and 11 don't have them. They are handy for JSON, SQL, HTML, XML and expected test output: the text looks the same as in a separate file, with no \n, \" or concatenation. All processing happens at compile time, so a text block is no slower than a regular literal at run time.

2. 

What are the rules for the opening and closing delimiters of a text block?

  • After the opening """ only spaces are allowed up to the end of the line, and then a line break is mandatory. The content starts on the next line.
  • You can't write a block on a single line: """Hello""" fails with illegal text block open delimiter sequence, missing line terminator. This is the difference from Python and Kotlin.
  • The closing """ goes either on a line of its own (then the string ends with \n) or right after the last character of the text (then there's no \n).
  • If the closing quotes are on the line right after the opening ones, the result is an empty string: isEmpty() returns true.
3. 

How does the Java compiler strip indentation in a text block?

The compiler removes the common indentation — incidental whitespace that comes from formatting the code. It finds the smallest number of leading whitespace characters and cuts exactly that many from every line, so relative indentation inside the text is preserved.

String html = """
        <ul>
            <li>Java</li>
        </ul>
        """;
// "<ul>\n    <li>Java</li>\n</ul>\n"

The minimum is computed over all non-blank lines and the closing delimiter line, if it contains only whitespace and """. Empty and whitespace-only lines don't count and become empty. Indentation is counted in characters, not screen columns: a tab and a space weigh the same, so mixing tabs and spaces gives unexpected results. The -Xlint:text-blocks option catches such cases.

4. 

How does the position of the closing delimiter affect the string a text block produces?

  • Right after the text — no trailing newline: "Hello\nWorld".
  • On its own line, aligned with the text — the string ends with \n: "Hello\nWorld\n". The most common choice.
  • On its own line, left of the text — the gap becomes the indentation of every line: a 4-space shift gives " Hello\n World\n".
  • On its own line, right of the text — same as aligned: the text sets the minimum. You can't add indentation this way; use indent(n) for that.

To keep the quotes on their own line but drop the trailing newline, end the last line with a backslash: World\.

5. 

Which escape sequences work in a text block, and what are \s and \<line-terminator> for?

All the escapes of regular strings work: \n, \t, \", \\, \040, \uXXXX. Single and double quotes don't need escaping — only three quotes in a row do, otherwise they close the block. Escaping one of the three is enough: \""" or ""\".

Two escapes were added specifically for text blocks:

  • \s — a single space that won't be stripped. The compiler silently removes trailing spaces on every line, so a needed trailing space is written as \s or \040. \s works in regular strings too (Java 15+).
  • \<line-terminator> — a backslash at the end of a line: the line break doesn't go into the result, and the next line is joined to the current one. The space before \ is kept. This is how a long single-line string is split across several lines of code.

Java has no raw strings: the regular expression \d+ is still written as \\d+ in a text block.

6. 

In what order does the compiler process a text block, and what line endings does the result have?

  1. Line terminators \r\n and \r are replaced with \n.
  2. The common leading indentation and the trailing spaces of each line are removed.
  3. Escape sequences are translated: \n, \t, \s, \", \<line-terminator> and the rest.

Because of step 1, a text block always contains \n (LF), even if the source is saved on Windows with CRLF: the result is the same on any OS. If you need platform line endings, replace them explicitly: s.replace("\n", System.lineSeparator()); if you need \r\n, write \r at the end of the lines.

Because of step 3, a \n inside a line doesn't create a new line for the indentation calculation, and \s, \040 and \t take part in neither indentation nor trailing-space removal.

7. 

How do you insert variable values into a text block, and which String methods are related to it?

Java has no interpolation like ${name}: a text block is a constant computed at compile time. Values are inserted with the formatted() method (Java 15), which works like String.format():

String html = """
        <p>Hello, %s!</p>
        """.formatted("Anna");

String Templates (STR."...") were a preview in Java 21 and 22 and were removed in Java 23. For SQL, never put values into the text — use PreparedStatement parameters.

Methods that repeat the block processing at run time — for strings from a file or from outside:

  • stripIndent() — removes the common indentation and trailing spaces using the compiler's algorithm;
  • translateEscapes() — turns escape sequences written as text into characters; throws IllegalArgumentException on an unknown sequence (\x) and on \uXXXX;
  • indent(n) (Java 12) — adds or removes n spaces at the start of each line and ends every line with \n.
8. 

Is a text block a constant: can you compare it with == and use it in a case label?

Yes. A text block is a string literal just like "...": a constant expression evaluated at compile time and interned in the string pool. So a block and a regular literal with the same content are the same object:

String h1 = "hello\n";
String h2 = """
        hello
        """;
System.out.println(h1 == h2); // true

Don't rely on == in real code anyway — compare strings with equals(). The practical benefit of being a constant: a text block can be used in a case label, an annotation value and a static final field. Once you call a method on the block (formatted(), strip()), the result is created at run time and isn't allowed in a case: constant string expression required.

Page 1 of 1