Sub topic 7
Writing Multi-Line Strings with Text Blocks
Before text blocks, a multi-line string in Java meant quotes, \n escapes and + on every line. A text block is a string literal that spans several lines and keeps its layout. This chapter covers the syntax, the rules for the opening and closing delimiters, how quotes behave, and the errors people hit most often.
You need these prerequisites:
- Basic Java syntax.
- Familiarity with
Stringand the+operator. - A JDK 15 or later. Text blocks were a preview feature in Java 13 and 14 and became standard in Java 15.
The next chapter covers indentation stripping in detail. This one covers only as much of it as you need to read the examples.
The Problem Text Blocks Solve
Suppose you need a small JSON document in a string. With ordinary literals you write this:
String json = "{\n" +
" \"name\": \"Ada\",\n" +
" \"age\": 36\n" +
"}\n";Every line needs a closing quote, a \n, a + and escaped inner quotes. The visual shape of the JSON is buried under the Java syntax. A mistake such as a missing \n produces output that is wrong but still compiles.
A text block removes that noise:
public class TextBlockDemo {
public static void main(String[] args) {
String json = """
{
"name": "Ada",
"age": 36
}
""";
System.out.print(json);
System.out.println(json.length());
}
}The program prints the four lines of JSON followed by 33. The 33 characters are the four lines plus four line feeds, with no indentation left over.
A Text Block Is Just a String
A text block is not a new type. It is another way to write a String literal. The compiler turns it into an ordinary String constant, so everything you know about String still applies:
- It is immutable.
- It is interned, like any other compile-time constant. A text block and a regular literal with identical content are the same object.
- You can pass it anywhere a
Stringfits: method arguments,+concatenation,String.format,switchcase labels and annotation values.
public class TextBlockIsString {
public static void main(String[] args) {
String a = """
hi""";
String b = "hi";
System.out.println(a.equals(b)); // true
System.out.println(a == b); // true, both are the same interned constant
}
}Compare with equals, as you always do. The == result above holds only because both values are compile-time constants.
Anatomy of a Text Block
A text block has three parts.
- The opening delimiter. It is three double quotes,
""", followed by optional spaces and then a line terminator. Nothing else may follow on that line. - The content. It starts on the line after the opening delimiter and runs to the closing delimiter.
- The closing delimiter. It is three more double quotes, either at the end of the last content line or on a line of its own.
The order of the processing steps matters. Escape sequences are interpreted last, so an escape such as \n or \t is never mistaken for source whitespace and cannot be stripped.
The line break after the opening delimiter
Content may not start on the same line as the opening """. Both of these fail to compile:
String bad1 = """hello"""; // error: illegal text block open delimiter sequence
String bad2 = """ hello
"""; // error: content on the opening lineThe rule keeps the layout predictable. The first content line is always a full line, so its indentation can be compared with the other lines.
The closing delimiter controls the final newline
The closing delimiter decides whether the string ends with a line feed. Put it on its own line and the last content line keeps its newline. Put it directly after the last character and no newline is added.
public class ClosingDelimiter {
public static void main(String[] args) {
String withNewline = """
hi
""";
String withoutNewline = """
hi""";
System.out.println(withNewline.equals("hi\n")); // true
System.out.println(withoutNewline.equals("hi")); // true
System.out.println(withNewline.length()); // 3
System.out.println(withoutNewline.length()); // 2
}
}This is the most common source of off-by-one surprises. If your output has an unexpected blank line at the end, the closing delimiter is probably on its own line. If a file you write has no final newline, it is probably glued to the last line.
The closing delimiter also affects indentation. Its position counts when the compiler decides how much leading whitespace to remove, which is why the JSON example above sits flush with the braces. The next chapter explains this rule.
Line Endings and Trailing Spaces
The compiler normalizes line terminators. Whether your source file uses LF (\n), CRLF (\r\n) or CR (\r), every line break inside a text block becomes a single \n in the resulting string. The same source therefore gives the same string on Windows, Linux and macOS. If you need \r\n in the output, write the escape \r\n explicitly, or convert afterwards with replace.
Trailing spaces and tabs at the end of each content line are removed. This protects you from invisible whitespace that editors add or drop. It also means you cannot keep deliberate trailing spaces just by typing them. The \s escape exists for that purpose and is covered in the chapter on escapes.
public class TrailingSpaces {
public static void main(String[] args) {
// The first line below has three trailing spaces in the source file.
String s = """
abc
def
""";
System.out.println(s.length()); // 8: "abc\ndef\n"
}
}Quotes Inside a Text Block
Single double quotes need no escaping, and neither do apostrophes. This is the main reason text blocks are comfortable for JSON, HTML and SQL.
public class Quotes {
public static void main(String[] args) {
String html = """
<a href="https://example.com" class='link'>Say "hello"</a>
""";
System.out.print(html);
}
}The only sequence you must handle is three consecutive double quotes, because they would end the block. Escape at least one of the three:
public class TripleQuotes {
public static void main(String[] args) {
String s = """
Three quotes: \""" end
""";
System.out.print(s); // Three quotes: """ end
}
}A text block that ends with a quote character has a related edge case. "hi"""" would be read as the closing delimiter followed by stray quotes. Put a line break before the closing delimiter, or escape the last quote as \".
A Realistic Example: Embedded SQL
Embedded query text is a good fit, because the query stays readable and can be copied to and from a database console without edits.
public class SqlExample {
public static void main(String[] args) {
String query = """
SELECT id, name
FROM customers
WHERE active = true
ORDER BY name
""";
System.out.print(query);
}
}The newline between lines is whitespace to SQL, so the query runs as written. Be careful when a line ends where a space was needed. This is the case if you join lines with the line-continuation escape described later, or if you delete a line break. For instance, joining FROM customers and WHERE without any whitespace gives customersWHERE.
A text block is not safe against injection. Never splice user input into SQL by building the string yourself. Use a PreparedStatement with ? placeholders. A text block holding the query template works well with that:
String template = """
SELECT id, name
FROM customers
WHERE country = ?
""";Rules at a Glance
| Rule | Behavior |
|---|---|
| Opening delimiter | `"""` plus optional spaces, then a line break. No content on that line. |
| Closing delimiter on its own line | The string ends with `\n`. |
| Closing delimiter after the last character | No final `\n` is added. |
| Line terminators | CR, LF and CRLF all become `\n`. |
| Trailing whitespace on a line | Removed. |
| `"` and `'` | Need no escaping. |
| `"""` inside the content | Escape at least one quote, for example `\"""`. |
| Type | An ordinary `String`, interned like any constant. |
Common Errors
- Content after the opening delimiter.
"""abcis a compile error. Start the content on the next line. - An unexpected blank line at the end. The closing delimiter sits on its own line. Move it up to the last content line if you do not want the final
\n. - Indentation that looks wrong. The position of the closing delimiter and the least-indented content line decide how much whitespace is removed. Chapter 7 covers this.
- Mixed tabs and spaces. The compiler counts a tab as one whitespace character, the same as a space. If two lines look aligned in your editor but use different characters, the stripping will not match what you see. Use one kind of whitespace throughout a block.
- Lost trailing spaces. They are always removed. Use
\swhere a trailing space matters. - Using
==to compare results. Strings built at run time, for example withformatted, are not interned. Useequals.
When to Use a Text Block
Text blocks suit content that is naturally multi-line and contains many quotes or backslashes. Typical cases are JSON, XML, HTML, SQL, regular expressions with many escapes, shell scripts and expected output in tests. For a single line, an ordinary literal is simpler. Concatenation inside loops is still a job for StringBuilder, because a text block is a fixed constant and does not grow.
Exercise
What does """ followed by hello on the same line do, and how do you fix it?
Show answer
It is a compile error, because the opening delimiter must be followed only by optional spaces and a line break. Move hello onto the next line, with the closing """ after it (for example, directly after hello if you do not want a trailing newline).
Exercise
Given the two blocks below, what are a.length() and b.length(), and why do they differ?
String a = """
ok
""";
String b = """
ok""";
Show answer
a.length() is 3 and b.length() is 2. In a, the closing delimiter is on its own line, so the string is ok\n. In b, the closing delimiter follows ok directly, so no newline is added and the string is ok.
Exercise
How do you write a text block whose content contains the three characters """?
Show answer
Escape at least one of the quotes, for example \""" or ""\". Without an escape, the compiler reads the three quotes as the closing delimiter.