Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 201 ยท Strings

Text Blocks and Escape Sequences

Write multi-line strings with Java text blocks - indentation rules, the closing delimiter, \ and \s escapes - plus every escape sequence and JSON, SQL and HTML examples.

Some characters can't be typed directly inside a string literal. A double quote would end the string, a backslash has a special meaning, and pressing Enter in the middle of "..." is a compile error. Escape sequences solve this: a backslash followed by a code, such as \n for a new line or \" for a quote.

Escapes are fine for a word or two, but a JSON document or a SQL query built from "\n" and "\"" quickly becomes unreadable. Since Java 15, text blocks let you write multi-line strings exactly as they should look, between triple quotes. This lesson covers both: every escape sequence, then text blocks in depth, including the indentation rules that confuse almost everyone the first time.

Escape sequences

An escape sequence starts with a backslash \ and stands for one character. These are all of them:

Escape Character Typical use
\n line feed (new line) line breaks
\t tab simple column alignment
\" double quote quotes inside a string
\' single quote the char literal '\''
\\ backslash Windows paths, regexes
\r carriage return Windows line endings \r\n
\b backspace rare
\f form feed rare (old printers)
\s space keeps trailing spaces in text blocks (Java 15+)
\0 to \377 the character with that octal code legacy; avoid

Any other letter after a backslash, such as \d or \q, is a compile error: illegal escape character.

Java Escape sequences in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The backslash rule causes a "double escaping" headache with regular expressions. The regex language uses its own backslashes (\d means a digit), and Java needs each of those written as \\. So the regex \d+ becomes "\\d+" in Java, and a regex that matches one literal backslash, \\, becomes "\\\\". Regular Expressions covers this in depth.

For file paths, you rarely need backslashes at all. Path.of("C:", "Users", "sam", "notes.txt") builds a path with the right separator for the operating system, and forward slashes work on Windows too. See Reading and Writing Files.

Unicode escapes

Separately from the table above, Java has Unicode escapes: \u followed by exactly four hexadecimal digits, such as \u0041 for A or \u00e9 for รฉ. They let you write any character using only ASCII in your source file.

Unicode escapes are special: the compiler translates them before it does anything else, even before it finds comments and strings. That leads to a famous trap. A comment that mentions a Windows folder like C:\users\demo contains \u followed by sers, which isn't four hex digits, so the file doesn't compile at all:

Java
// Files live in C:\users\demo   <- compile error: illegal unicode escape

Today, source files are UTF-8 by default, so you can usually type characters such as รฉ directly. Unicode escapes are still handy for invisible characters, such as the non-breaking space \u00a0, where seeing the code is clearer than seeing nothing. Character Sets and Encoding explains UTF-8 and friends.

Text blocks

A text block is a string literal that spans several lines. It starts with three double quotes followed by a line break, and ends with three double quotes:

Java Your first text block

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Both versions produce exactly the same String; a text block is just a nicer way to write the literal. Quotes need no escaping, line breaks are real line breaks, and the indentation in your code doesn't end up in the text. The result is an ordinary String with all the usual String Methods.

Two rules about the opening delimiter:

  • Nothing but whitespace may follow the opening """ on its line. String s = """Hello"""; is a compile error. For one-line text, use a normal string.
  • The content starts on the next line, so that first line break is not part of the string.

How indentation works

The most important thing to understand about text blocks is how Java decides which spaces are part of your text. Your code is indented to fit the surrounding method, but you don't want those spaces in the string. Java removes them with a simple rule:

  1. Look at every non-blank content line, plus the closing """ line if the closing delimiter is on its own line.
  2. Find the smallest number of leading spaces among them.
  3. Remove that many spaces from the start of every line.
  4. Remove trailing spaces from the end of every line.

The removed whitespace is called incidental; what stays is essential. In practice, the leftmost line (or the closing delimiter) marks the left edge of your text. Run this example to see the effect, with each space shown as a dot:

Java The closing delimiter sets the margin

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Compare the three results:

  • a: The text and the closing delimiter start in the same column, so all that indentation is removed. green keeps its two extra spaces, because they're beyond the margin. The string ends with a newline, because the closing """ is on the next line.
  • b: The closing delimiter is four spaces further left than the text, so it sets the margin, and every line keeps four extra spaces. Moving the closing delimiter left is how you add indentation on purpose.
  • c: The closing delimiter comes right after blue, so there is no trailing newline. It no longer counts for the margin, so the leftmost content line decides.

Don't mix tabs and spaces for indentation inside a text block. Java counts each whitespace character as one, so a tab and a space count the same, and the margin can end up somewhere you didn't expect. Let your editor indent with spaces.

Escapes inside text blocks

Text blocks still process escape sequences, and add two that are most useful in them:

  • \ at the end of a line joins it with the next line, so you can break a long line in the source without putting a newline in the string.
  • \s is a single space that is never stripped. Use it to keep trailing spaces, which would otherwise be removed.

Single and double quotes can be written freely. Only a run of three double quotes needs escaping, as \""", because it would otherwise end the block.

Java Line continuation, \s and quotes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In the table, each line ends with spaces and then \s. The spaces before \s are kept too, because trailing-space stripping only removes whitespace at the very end of a line, and \s is not stripped. Without it, the lines would come out at different lengths.

Two more details are worth knowing:

  • Line endings are normalized. Whether your source file uses Windows (\r\n) or Unix (\n) line endings, every line break in a text block becomes \n. If you need \r\n, for example for an HTTP or CSV format that requires it, write \r at the end of each line or call .replace("\n", "\r\n").
  • Escapes are processed last. Indentation is stripped first, then escapes are translated. That's why a \n escape in a line doesn't confuse the margin calculation, and why \s and \ work the way they do.

Inserting values

Text blocks have no built-in interpolation: ${name} is just text. To insert values, combine a text block with formatted(), which you learned in Formatting Strings:

Java Templates with formatted()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The record line defines a tiny data class; you'll learn about Records later. Notice the SQL query uses a ? placeholder instead of %s.

Never format untrusted input into SQL, HTML or JSON. If a customer's name contains ' or <script>, a plain formatted() puts it straight into your query or page, which is how SQL injection and cross-site scripting attacks happen. For SQL, keep ? placeholders and use a PreparedStatement (covered in the Advanced Java track). For HTML, escape the values; for JSON, use a library that builds the document for you. Text block templates are perfect for fixed structure and trusted values.

Helper methods for multi-line text

Three String methods were added alongside text blocks. They let you apply the same rules to strings that come from elsewhere, such as a file or a resource:

  • stripIndent() removes incidental indentation using the text block algorithm.
  • translateEscapes() turns escape sequences written as text, like a backslash followed by n, into the real characters.
  • indent(n) adds n spaces to the start of every line (or removes them if n is negative), and makes sure the result ends with a newline.
Java stripIndent, translateEscapes and indent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

When to use text blocks

Text blocks are a great fit whenever the text has several lines or lots of quotes:

  • JSON and XML test fixtures and sample payloads.
  • SQL queries, where line breaks make the clauses readable.
  • HTML and email templates with a fixed structure.
  • Expected output in tests, which you can paste in exactly as the program prints it.
  • Help text, usage messages and ASCII art.

For a short, single-line string, stick with a normal literal. And if a text block grows past a screen or so, consider moving it to a resource file and loading it with Files.readString.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does "a\\nb".length() return?

    In Java source, \\ is one backslash character, so the string holds a, a backslash, n and b: four characters. ("a\nb" with a single backslash would be 3.)
  2. 2. Why doesn't String s = """Hello"""; compile?

    Only whitespace may follow the opening delimiter on its line. The content always starts on the next line.
  3. 3. A text block's closing """ sits at the end of its last content line. What changes?

    When the closing delimiter is on its own line, the last line break is part of the string. Putting it right after the text leaves that newline out.
  4. 4. In a text block, every content line is indented 8 spaces and the closing """ is on its own line indented 4 spaces. How many leading spaces does each line of the result have?

    The closing delimiter line counts when Java finds the smallest indentation. The margin is 4, so 4 of the 8 spaces are removed and 4 remain.
  5. 5. What is the purpose of \s in a text block?

    Trailing whitespace is normally removed from each line. \s is a real space that survives, and it also protects the spaces before it.

Summary

  • Escape sequences such as \n, \t, \", \' and \\ stand for single characters; in regexes you need double backslashes like "\\d".
  • Unicode escapes (\u0041) are processed before everything else, even in comments, so C:\users in a comment breaks compilation.
  • A text block starts with """ and a line break, ends with """, and produces an ordinary String. Quotes and newlines need no escaping.
  • Java removes the incidental indentation: the smallest indentation among content lines and the closing-delimiter line. Move the closing """ left to keep indentation; put it after the last line to drop the trailing newline.
  • Trailing spaces are stripped; \s keeps them. A \ at the end of a line joins it to the next. Line breaks are always \n.
  • Use formatted() to fill text block templates, but never with untrusted input for SQL, HTML or JSON.
  • stripIndent(), translateEscapes() and indent(n) apply the same ideas to any string.

Next: StringBuilder, the fast way to build strings piece by piece in loops.