liveBook · Manning

Escape sequence

As explained in 100 Java Mistakes and How to Avoid Them

An escape sequence is a backslash-initiated notation in a string or character literal that represents a special character or character value.

An escape sequence is a backslash-initiated notation in a Java string or character literal. Common sequences represent a line break (\n), tab (\t), quote, carriage return (\r), backspace (\b), or form feed (\f). Java 15 text blocks also support \s for one space. section 6.7

The path that silently changes

A Windows path can compile while producing the wrong string: String archiverPath = installationPath + "\\bin\\tar.exe"; Here, an accepted escape such as \b or \t is interpreted by Java, so the result contains a backspace or tab instead of the intended directory characters. Escape the backslash explicitly, or construct the path with path components: Path archiverPath = Path.of(installationPath, "bin", "tar.exe"); section 6.7

Forgetting a backslash usually causes a compilation error because only certain characters may follow it. The dangerous cases are the valid escapes that change the literal without producing an error. Regular expressions add another interpretation: Java processes the literal first, then the regular-expression engine processes the resulting pattern. Most common escapes retain compatible meanings, but \b is different: Java makes it a backspace, whereas a regular expression treats it as a word boundary. section 6.7

Prevent accidental escape-sequence behavior by:

  • Checking every backslash in literals, especially paths and regular expressions. section 6.7
  • Distinguishing Java literal escaping from regular-expression escaping; inspect the resulting pattern when both apply. section 6.7
  • Using IDE highlighting to spot sequences such as \b and \t, while remembering that static analysis cannot replace semantic review. section 6.7

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains common escapes, silent literal changes, regex double interpretation, and path-based prevention.
Examples
Uses Windows paths, regex word boundaries, IDE highlighting, and Path.of as concrete examples.
What it assumes
Assumes familiarity with Java literals, strings, regular expressions, and filesystem paths.
What you can do after
Diagnose silently altered literals and construct paths or regex patterns with the required escaping.
How it connects
Connects string literals, character literals, regular expressions, text blocks, Windows paths, and filesystem path construction.

Also explained in

Compare how 6 books explain escape sequence →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.