Sub topic 9
Escapes: Line Continuation, \s and Quotes
This chapter assumes you can read basic Java and know how a String literal handles \n, \t and \". It also assumes you have seen the text block syntax (""" delimiters) and how indentation is stripped, both covered in earlier chapters. You need JDK 15 or later to run the examples.
Text blocks keep most characters as written, but a few things you cannot type directly, or do not want to type, need escape sequences. This chapter covers the three escapes that matter most in text blocks: the line continuation backslash, \s, and escaped quotes. It also explains the order in which the compiler handles them, which settles most of the surprising cases.
The order of processing
A text block is not read literally. The compiler transforms its content in three steps, always in this order:
- Line terminators are normalized. Whether your file uses
\n,\r\nor\r, each one becomes a single\n. - Incidental whitespace is stripped. The common leading indentation is removed, and trailing spaces and tabs are removed from every line.
- Escape sequences are interpreted.
The order has two practical consequences:
- An escape cannot influence indentation stripping. A line that starts with
\thas no leading whitespace as far as step 2 is concerned, because the backslash is the first character. - An escape can protect whitespace from stripping. Step 2 only removes real space and tab characters. A
\sor\tis still plain text at that point, so it survives.
Line continuation with a trailing backslash
A backslash as the very last character on a line removes the line break after it. The two source lines become one line of text.
public class Continuation {
public static void main(String[] args) {
String sql = """
SELECT id, name \
FROM users \
WHERE active = 1\
""";
System.out.println(sql);
System.out.println(sql.length());
}
}This prints:
SELECT id, name FROM users WHERE active = 1
43The result has no trailing newline. The last content line ends with \, so the line break before the closing delimiter is removed too, and the closing line contributes only indentation, which step 2 strips. This is the usual way to get a text block with no final newline.
Three details are easy to miss:
- The space before each backslash is part of the text. If you write
name\instead ofname \, the output containsnameFROM. The compiler does not add separators. - Indentation on the continued line is stripped as usual. The word
FROMstarts at column 16 in the source, but the 16 columns are incidental whitespace and do not appear in the output. - The backslash must be the last character on the line. A space after it is a compile error (
illegal escape character), and editors that trim or add trailing whitespace can cause this. If you see that error on a line that looks fine, check for an invisible trailing space.
Line continuation exists only in text blocks. A regular "..." literal cannot span lines, so a backslash-newline there is a compile error.
Keeping trailing spaces with \s
Step 2 removes trailing spaces from every line, which is usually what you want, since editors often add them by accident. When you need trailing spaces, such as fixed-width columns, use \s. It is the escape for a single space character (U+0020).
Because escapes are interpreted after stripping, \s is not whitespace when the stripping happens. Everything before it is kept as well.
public class Padding {
public static void main(String[] args) {
String padded = """
red \s\s
green\s\s
blue \s\s
""";
for (String line : padded.split("\n")) {
System.out.println("[" + line + "] " + line.length());
}
}
}Output:
[red ] 7
[green ] 7
[blue ] 7Each line is padded to seven characters. The plain spaces between red and \s\s survive because they are no longer at the end of the line from the stripper's point of view. A single \s at the end is enough to protect all the spaces before it.
\s also works in regular string literals since Java 15, so "a\sb" is "a b". It is rarely useful there, since you can type a space.
A common alternative to \s is the octal escape \040, which is also a space. \s is more readable and is the better choice.
Quotes inside text blocks
A single " or a pair "" can appear in a text block without escaping. Only a run of three quotes ends the block, so ordinary prose and JSON need no backslashes.
public class Quotes {
public static void main(String[] args) {
String a = """
He said "stop" and then ""quietly"" left.
""";
System.out.print(a);
String b = """
Three quotes: \""" done
""";
System.out.print(b);
String c = """
"Quoted\"""";
System.out.println(c);
}
}Output:
He said "stop" and then ""quietly"" left.
Three quotes: """ done
"Quoted"The three cases show the rules:
- In
a, single and double quotes are literal. - In
b,\"""produces three quote characters. Escaping the first quote is enough. The following two are then a harmless pair. - In
c, the content ends with a quote, and the closing delimiter sits on the same line. The compiler reads\"as an escape first, so the next three quotes close the block. Without the backslash you would write four quotes in a row, and the first three would close the block, leaving a stray"and a syntax error.
If you put the closing delimiter on its own line, as in most examples, you avoid case c entirely. The text then ends with a newline, which you can remove with a trailing \ on the last content line.
A single quote needs no escape in either kind of literal. \' is accepted but redundant.
Other escapes you can use
All the escapes from regular strings work in text blocks. Their meaning does not change, but their interaction with stripping may differ from what you expect.
| Escape | Meaning | Note |
|---|---|---|
| `\n` | Line feed | Adds a line break without a new source line |
| `\t` | Tab | Survives stripping, even at the start or end of a line |
| `\r` | Carriage return | Kept as an actual CR, unlike a CR in the raw source |
| `\b`, `\f` | Backspace, form feed | Rarely needed |
| `\"` | Double quote | Required only to form `"""` or at the end of the block |
| `\\` | Backslash | Needed for every literal backslash, such as in regex and Windows paths |
| `\s` | Space | Protects trailing spaces |
| `\<newline>` | Line continuation | Text blocks only |
| `\0` to `\377` | Octal character code | Rarely needed |
Here is how the processing order affects a leading \t:
public class TabEscape {
public static void main(String[] args) {
String t = """
\tindented by an escape
plain
""";
System.out.print(t.replace("\t", "<TAB>"));
}
}Output:
<TAB>indented by an escape
plainBoth lines and the closing delimiter share the same four-space indentation, so that is what step 2 removes. The \t is not whitespace to the stripper, so it stays, and step 3 turns it into a tab. If you had typed a real tab character at the start of the first line, it would have counted as incidental whitespace and could change the computed indentation. That is the reason to write \t for tabs you want to keep.
Regular expressions are where \\ is most common, because the regex needs a backslash and Java needs it escaped:
String pattern = """
\\d{3}-\\d{4}"""; // the regex \d{3}-\d{4}Unicode escapes are different
An escape like \u0022 is not handled in step 3. The compiler translates \uXXXX sequences in the whole source file before it does any other parsing. A \u0022 is therefore a plain quote when the compiler reads the block, and three of them in a row would end it. This is a poor way to include quotes. Use \" or place the quotes so they never appear three times in a row.
Common errors
- Trailing space after a line-continuation backslash. This gives
illegal escape character. Remove the space and configure your editor to show or strip trailing whitespace. - Missing space before a continuation backslash. The words run together in the output.
- Expecting trailing spaces to survive. Without
\s, they are removed silently. - A lone backslash in a regex or path.
\dandC:\temp\neware not valid or do not mean what you think. Use\\dandC:\\temp\\new. - Content ending in a quote with the closing
"""on the same line, without\". This is a syntax error. - Using
\nto build the whole text, which defeats the point of a text block. Use real line breaks and keep\nfor the cases where you need an extra newline inside one source line.
Escapes in strings you already have
If a string contains literal backslash sequences that came from somewhere else, such as a file or user input, the compiler will not interpret them. String.translateEscapes() applies the same step-3 rules to an existing string at run time. The chapter on text block methods covers it.
Exercise
What does this program print, and how many characters long is s?
String s = """
a \
b\s
c
""";
System.out.print(s);
Show answer
It prints a b followed by a newline and then c and a newline. The first backslash joins a and b into a b. The \s after b adds one space, and the line break after it stays. The text is "a b \nc\n", so s has 8 characters: a, space, b, space, newline, c, newline is 7 characters. Counting precisely: a(1) space(2) b(3) space from \s(4) newline(5) c(6) newline(7). The length is 7.
Exercise
A text block contains a SQL statement across three source lines. The result must be a single line with no trailing newline, and the compiler reports illegal escape character on the second line, which ends with FROM users \. What is the most likely cause, and how do you fix it?
Show answer
The backslash is probably followed by an invisible trailing space or tab, so it is not the last character on the line and is read as an invalid escape. Remove the whitespace after the backslash. If your editor adds trailing whitespace automatically, turn on its trailing-whitespace trimming or visualization.
Exercise
Write a text block assigned to String box that produces exactly the two lines [ ok ] and [fail], where the first line must keep one space at the end of its content padding, so each line is 6 characters wide, with no extra trailing newline.
Show answer
One solution:
String box = """
[ ok ]
[fail]\
""";
Both lines are already 6 characters, so no \s is needed. The \ after [fail] removes the final line break, so the text is "[ ok ]\n[fail]". If you needed a trailing space inside a line, you would end that line with \s before the line break.