Text blocks for multi-line strings
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A JSON message or an SQL query needs \n, quotes and + on every line. It is hard to read and easy to break.
Text blocks (Java 15) with triple quotes
A text block is a multi-line String literal written between triple quotes, keeping line breaks without \n or + joins.
Before Java 15, a multi-line string meant gluing pieces together: "{\n" + " \"name\": \"Asha\"\n" + "}". Every line needs \n, every quote needs a backslash, and one missing + or \n breaks the output. It is hard to read and easy to get wrong.
Example 1 · Old concatenation vs a text block
public class TextBlockBasicsDemo { public static void main(String[] args) { String oldJson = "{\n" + " \"name\": \"Asha\",\n" + " \"course\": \"BCA\",\n" + " \"year\": 2\n" + "}\n";
String json = """ { "name": "Asha", "course": "BCA", "year": 2 } """;
System.out.print(json); System.out.println("Same text: " + oldJson.equals(json)); System.out.println("Lines: " + json.lines().count()); }}{
"name": "Asha",
"course": "BCA",
"year": 2
}
Same text: true
Lines: 5What this code does
- The text block needs no
\n, no+and no\". It produces exactly the same string as the concatenated version, soequalsistrue. - The closing
"""is on its own line, so the string ends with a line break, which is whyprint(notprintln) is enough. The common indentation of 16 spaces is removed.
- Open:
"""then a new line. Close:"""anywhere. "inside needs no backslash; only"""would end the block.- Escapes like
\nand\tstill work inside. - Text blocks are standard from Java 15, so they work on Java 17.
A text block starts with """ followed by a line break, and ends with """. Everything between is the string, line breaks included. Double quotes inside need no escaping. The result is an ordinary String: length(), equals and + work as usual. The opening """ must be the last thing on its line. """Hello""" on one line is a compile error, because a text block is meant for several lines.
How indentation is removed
Text blocks sit inside indented code, so their lines start with spaces that are not meant to be part of the string. Java removes this incidental indentation for you.
- Find the content lines and the closing
"""line. - Take the smallest number of leading spaces among them (blank lines do not count).
- Remove that many spaces from the start of every line.
- Remove spaces at the end of every line.
- Then process escapes such as
\n,\sand a backslash at line end.
Example 2 · Where the closing delimiter goes changes the indentation
public class TextBlockIndentDemo { static void show(String label, String text) { System.out.println(label); text.lines().forEach(line -> System.out.println("[" + line + "]")); System.out.println("ends with newline: " + text.endsWith("\n")); }
public static void main(String[] args) { String aligned = """ Roll 14 Maths 91 """; String moreRoom = """ Roll 14 Maths 91 """; String noNewline = """ Roll 14 Maths 91""";
show("closing lined up with the text:", aligned); show("closing 4 spaces further left:", moreRoom); show("closing at the end of the last line:", noNewline); }}closing lined up with the text: [Roll 14] [ Maths 91] ends with newline: true closing 4 spaces further left: [ Roll 14] [ Maths 91] ends with newline: true closing at the end of the last line: [Roll 14] [ Maths 91] ends with newline: false
What this code does
- Java removes the smallest indentation it sees among the lines and the closing
""". Moving the closing delimiter 4 spaces left makes every line keep 4 extra spaces. The extra 2 spaces beforeMathsare always kept. - With
"""at the end of the last content line, the string has no final line break. The brackets show exactly where each line starts and ends.
It finds the smallest indentation among the content lines and the closing """ line, and strips exactly that much from every line.
So the closing delimiter is a control. Put it on its own line, lined up with the text, and the text starts at column 0. Move it further left, and every line keeps the extra spaces between it and the text. Lines indented more than the others keep their extra spaces, which is how nested JSON keeps its shape.
The closing position also decides the last line break. If """ is on its own line, the string ends with \n. If it is at the end of the last content line, there is no final \n.
Order of execution
How Java prepares a text block
Tap the steps in the order Java applies them.
Escapes: backslash at line end and \s
Two escapes were added for text blocks. A backslash at the end of a line joins that line with the next one, with no line break between them.
Example 3 · Escapes: joining lines, \s and triple quotes
public class TextBlockEscapesDemo { public static void main(String[] args) { String notice = """ Fee payment for semester 5 closes on 30 September. \ Late payment adds a fine of Rs 500. """; System.out.print(notice);
String padded = """ Name \s Marks \s """; padded.lines().forEach(line -> System.out.println("[" + line + "] length " + line.length()));
String quote = """ The examiner said "well done". A Java text block starts with \""" and a new line. """; System.out.print(quote); }}Fee payment for semester 5 closes on 30 September. Late payment adds a fine of Rs 500. [Name ] length 9 [Marks ] length 9 The examiner said "well done". A Java text block starts with """ and a new line.
What this code does
- The backslash at the end of the first line joins it to the next, so the notice is one line in the string while staying readable in the code.
\sis a space that is never stripped, so both padded lines keep a width of 9. Plain double quotes need no escape; three in a row are written\""".
Use it to split a long sentence across lines in the code while keeping it one line in the string.
\s stands for one space that is never removed. Java strips spaces at the end of each line, so a \s at the end keeps the line's width. It is also a clear way to show a space that matters.
To put three quotes in a row inside a text block, escape the first one: \""". Everything else, single and double quotes included, can be typed as is.
formatted for JSON, SQL and HTML templates
A text block is often a template: fixed text with a few blanks to fill. String.formatted(...) (Java 15) fills the blanks, using the same %s, %d and %.2f codes as String.format. """...%s...""".formatted(name) reads naturally: the template, then the values.
Example 4 · formatted for JSON, SQL and HTML templates
public class TextBlockTemplateDemo { static final String RECEIPT_JSON = """ { "receiptNo": "%s", "student": "%s", "amount": %.2f, "paid": %b }""";
static final String FEES_QUERY = """ SELECT roll_no, name, amount FROM fees WHERE semester = ? AND paid = ? ORDER BY roll_no""";
static final String EMAIL_HTML = """ <p>Dear %s,</p> <p>We received <b>Rs %,d</b> for semester %d.</p>""";
public static void main(String[] args) { System.out.println(RECEIPT_JSON.formatted("R-2041", "Pooja Nair", 45250.5, true)); System.out.println("---"); System.out.println(FEES_QUERY); System.out.println("---"); System.out.println(EMAIL_HTML.formatted("Pooja", 45250, 5)); }}{
"receiptNo": "R-2041",
"student": "Pooja Nair",
"amount": 45250.50,
"paid": true
}
---
SELECT roll_no, name, amount
FROM fees
WHERE semester = ? AND paid = ?
ORDER BY roll_no
---
<p>Dear Pooja,</p>
<p>We received <b>Rs 45,250</b> for semester 5.</p>What this code does
- Each template keeps the shape of the JSON, SQL or HTML it produces, and
formattedfills the%s,%.2f,%b,%,dand%dblanks in order.%,dadds thousands separators. - The SQL text block keeps
?placeholders. Real values go in later through aPreparedStatement, never pasted into the query text.
This is handy for building a JSON body for an API call, an HTML email such as a fee receipt, or a fixed SQL query to show in a log. Keep the template in a constant and fill it each time. For SQL that includes user input, do not paste values into the query text; that allows SQL injection, where crafted input changes the query. Use the text block for the query shape with ? placeholders, and pass the values separately through a PreparedStatement.
formatted returns a new string; the text block itself never changes. A % sign meant as text must be written %% in a template.Trap: trailing spaces are removed
Java strips spaces at the end of every line in a text block. Usually that is what you want, since editors add stray spaces.
Example 5 · Trap: padding at the end of a line disappears
public class TrailingSpaceTrapDemo { public static void main(String[] args) { String table = """ Item Price Pen 10 Folder 15 """; String broken = """ Pen Folder """; String fixed = """ Pen \s Folder \s """;
table.lines().forEach(line -> System.out.println("[" + line + "]")); broken.lines().forEach(line -> System.out.println("broken [" + line + "] " + line.length())); fixed.lines().forEach(line -> System.out.println("fixed [" + line + "] " + line.length())); System.out.println("formatted [" + "%-10s".formatted("Pen") + "]"); }}[Item Price] [Pen 10] [Folder 15] broken [Pen] 3 broken [Folder] 6 fixed [Pen ] 10 fixed [Folder ] 10 formatted [Pen ]
What this code does
- The
brokenlines were typed with spaces after the item names to make them 10 characters wide. Java strips trailing spaces, so they come out as 3 and 6 characters. - Ending the line with
\skeeps the padding;"%-10s".formatted(...)pads to a fixed width without typing spaces at all.
But if you build a fixed-width table and pad a cell with spaces at the end of a line, the padding silently disappears and length() changes.
The fix is \s at the end of the padded line, or building fixed-width lines with formatted and %-10s instead of typing spaces. A second, smaller trap: mixing tabs and spaces for indentation confuses the "smallest indentation" rule, so use spaces only.
Next step
Check your understanding
12 quick questions