Java illegal escape character: fix invalid string escapes

Why javac reports an illegal escape character, which backslash sequences Java accepts, and how to fix paths, regex patterns and pasted text without changing what the string means.

The illegal escape character error means javac found a backslash inside a string or character literal, followed by a character that Java does not define as an escape. The fix is usually one extra backslash. The right fix still depends on what the string is for: a file path, a regular expression, or text copied from another format. This guide covers what escaping changes, how to confirm that an escaped literal still means what you intended, and when it is better to avoid escaping altogether.

Short answer: is escaping the right fix?

For a short literal that really needs a backslash, doubling it (writing \ instead of ) is the standard fix. The main benefit is that the compiled string contains exactly the characters you meant. The main tradeoff is readability. Every layer of escaping makes the source harder to review and easier to get wrong. In a regular expression, one literal backslash takes four characters of source. Plain text kept outside the Java source is the better choice when the content is long, changes often, is edited by people who are not developers, or is data rather than code. In those cases, use a resource or configuration file, or a text block (with the caveats below).

What the error actually means

Java resolves backslash sequences in string and character literals at compile time. The language defines a fixed set of sequences. Any other backslash sequence is rejected; Java does not pass it through unchanged. That is why \d in a string literal is a compile error and not a backslash followed by the letter d.

Escape in source | Character in the compiled string
\b | backspace
\t | tab
\n | line feed
\f | form feed
\r | carriage return
\s | space (Java 15 and later)
" | double quote
' | single quote
\ | one backslash
\0 to \377 | character given by an octal code
\ followed by a line break | line continuation, text blocks only (Java 15 and later)

Every other sequence triggers the error, including \d, \w, ., \U, \p and /. The last one is valid in JSON and JavaScript but not in Java, so it often turns up when JSON is pasted into a Java literal.

What escaping changes, and what it should not

Escaping changes only how the string is written in the source file. The runtime value should be exactly the text you intended. For example, C:\temp written in a literal becomes the seven-character string C:\temp at runtime. Printing it shows a single backslash. Some debuggers and JSON viewers show strings in escaped form, so a doubled backslash in a variable view does not always mean the string contains two backslashes. Checking length() settles the question.

Several layers use the backslash, and they are easy to confuse. Java literal escapes are resolved by the compiler. Regex escapes are read by java.util.regex at runtime. JSON, properties files and shells each have their own rules. A single string may pass through more than one of these layers. Tools that say they escape text may target any one of them, and output escaped for JSON or regex differs from output escaped for Java. Using the wrong one can produce a literal that compiles but means something else.

Unicode escapes are a separate, earlier step

\uXXXX is not a string escape. The compiler translates Unicode escapes across the whole source file before it identifies literals, comments or anything else. This has several practical consequences:

  • A \u that is not followed by four hexadecimal digits causes a different error, illegal unicode escape. It can be triggered inside a comment, for example a comment that mentions a lowercase Windows path such as C:\users.
  • \u000A inside a string literal becomes a real line break in the source, which leaves the literal unterminated. Use \n instead.
  • \u0022 becomes a double quote and ends the string early. Use " instead.
  • Emoji and other characters outside the Basic Multilingual Plane need two \u escapes (a surrogate pair), because Java strings are UTF-16. Writing the character directly is usually clearer, as long as the compiler reads the file in the encoding it was saved in, for example by setting javac's -encoding option.

Fixing the common cases

Windows file paths

// Error: \U and \D are not valid Java escapes
String bad = "C:\Users\Dev\notes.txt";

// Fix 1: double every backslash
String a = "C:\\Users\\Dev\\notes.txt";

// Fix 2: forward slashes, which Java's file APIs accept on Windows
String b = "C:/Users/Dev/notes.txt";

// Fix 3: build the path from its parts
Path c = Path.of("C:\\", "Users", "Dev", "notes.txt");

In the broken example, fixing only the sequences javac complains about is not enough. The \n at the start of \notes is a valid escape, so it compiles without warning into a line feed. When you repair a path, check every backslash in the literal, not only the ones the compiler reports.

Regular expressions

The regex engine needs to receive \d, so the Java source must contain \d. To match one literal backslash, the regex engine needs \, so the source must contain four backslashes.

// Error: \d and \. are not Java escapes
Pattern bad = Pattern.compile("\d+\.\d+");

// Fix: escape each backslash for Java; the regex engine receives \d+\.\d+
Pattern ok = Pattern.compile("\\d+\\.\\d+");

// Match literal text without hand-writing regex escapes
Pattern lit = Pattern.compile(Pattern.quote("C:\\logs\\*.log"));

// Replacement strings give \ and $ special meaning too
String out = input.replaceAll("/", Matcher.quoteReplacement("\\"));

// No regex needed? String.replace treats both arguments literally
String same = input.replace("/", "\\");

The replacement argument of replaceAll and replaceFirst is parsed as well, and the backslash and dollar sign are special in it. Matcher.quoteReplacement makes a replacement literal. If you do not need pattern matching, String.replace with two plain strings avoids regex entirely.

Text copied from JSON, JavaScript or other languages

Sequences such as / (valid in JSON), \x41 (valid in JavaScript and C) or \e (valid in some shells and scripting languages) are not valid Java escapes. Before you paste already-escaped text into a Java literal, decode it back to plain text first, then escape it once for Java. Escaping text that is already escaped compiles without complaint but leaves extra backslashes in the runtime value.

Text blocks

Text blocks (triple-quoted literals, standard since Java 15) let you write double quotes and line breaks without escapes. They are not raw strings, though. Backslash escapes are still processed, so a regex or Windows path inside a text block still needs doubled backslashes. Java has no raw string literal; a proposal for one was withdrawn before release.

// Quotes need no escaping, but backslashes still do
String json = """
    {"path": "C:\\\\data"}
    """;
// Runtime text: {"path": "C:\\data"}
// A JSON parser then reads the value as C:\data

Will the escaped result stay usable?

The escaped form only belongs in Java source. If you copy it from the source into a terminal, file dialog or document, the doubled backslashes come with it. If you copy the runtime value from printed output or a log, you get plain text. Some editors can escape text automatically when it is pasted into a string literal. This behavior depends on the editor and its settings, so check the result instead of assuming it happened.

Escaping does not change what end users see; it affects only the people reading and searching the code. Searching a codebase for the runtime value C:\temp will not find a literal written as C:\temp. Search for the escaped form, or for a distinctive substring without backslashes.

When the text is user-facing, long, or meant to be edited outside the code, keep it as plain text in a resource file and read it at runtime. Java literal escaping then does not apply. Properties files are an exception to watch for. Properties.load treats the backslash as an escape and silently drops a backslash that comes before an unrecognized character. A path written as C:\temp in a properties file therefore loads with a tab in place of \t, and C:\Users loads as C:Users. Paths in properties files still need doubled backslashes or forward slashes.

Using an online or editor-based escaper

Escaping tools work well for turning a one-off block of text into a valid literal. Before trusting the output, check a few things. Does the tool treat your input as raw text or as text that is already escaped? Which characters does it change? Some tools convert all non-ASCII characters to \u escapes, which is valid but harder to read. Does it target Java specifically, or JSON or JavaScript? Avoid pasting secrets or private data into a web tool. Its appearance says nothing about whether input is logged or kept, so read its stated policy or use a local option. No specific escaping tool was evaluated for this guide.

Troubleshooting: the result is not what you expected

  • Illegal escape character at compile time: a backslash is followed by a character Java does not define as an escape. Check the column javac points to, then scan the rest of the literal. Fix it by doubling the backslash, or by using forward slashes for paths.
  • Illegal unicode escape, sometimes reported on a comment line: somewhere in the file, \u is not followed by four hexadecimal digits. Search comments and strings for \u, especially in lowercase Windows paths. Fix it by doubling the backslash or rewording the comment.
  • Unterminated string literal near a \u escape: \u000A, \u000D or \u0022 inside a literal turns into a line break or quote before the literal is read. Use \n, \r or " instead.
  • The code compiles, but a path or message contains a tab, a line break or missing characters: a valid escape such as \t or \n was used by accident. Check length(), or print the value between visible delimiters. Fix it by doubling the backslash.
  • The code compiles, but a regex does not match: it was escaped for Java but not for regex, for regex but not for Java, or twice. Print pattern() on the compiled Pattern to see exactly what the regex engine received.
  • Doubled backslashes appear at runtime: text that was already escaped has been escaped again, or a debugger or JSON view is showing the escaped form. Check length() to tell these apart.
  • Emoji or non-English text looks garbled: this may be an encoding mismatch between how the file was saved and how javac read it, not an escaping problem. To check, compile with an explicit encoding, or temporarily replace the affected characters with \u escapes and see whether the output changes.

Limits of this guide

This guide is based on Java language rules and documented standard library behavior. No particular escaping tool, editor or JDK build was tested, and the wording of compiler messages may differ between JDK versions and vendors. If the error remains after these checks, the quickest way to diagnose it is a minimal snippet that reproduces the problem, together with the exact compiler output.