Java String Escape & Unescape

Which characters are escaped?

CharacterJava escapeMeaning
\\\Backslash
"\"Double quote
newline\nLine feed (LF)
carriage return\rCR
tab\tHorizontal tab
backspace\bBackspace
form feed\fForm feed
any non-ASCII\uXXXXUnicode code unit (optional)

Text blocks (Java 15+)

Java's text block syntax ("""...""") removes most of the need to escape newlines and double quotes. Enable the checkbox above to wrap the output in a text block instead of a single-line literal.

String json = """
        {
          "name": "Alice",
          "age": 30
        }
        """;

Inside a text block, you only need to escape \\, \t (to force a tab rather than spaces), and a run of three or more quotes.

Doing it in code

Programmatic escaping is typically done with StringEscapeUtils from Apache Commons Text:

import org.apache.commons.text.StringEscapeUtils;

String literal = StringEscapeUtils.escapeJava(raw);
String back    = StringEscapeUtils.unescapeJava(literal);

Or, for a dependency-free alternative, use String.translateEscapes() (Java 15+) for unescaping.

Common uses

  • Pasting SQL, JSON or HTML into a test fixture
  • Preparing log messages or error strings with non-ASCII characters
  • Reversing a Java literal copied from a stack trace or source file
  • Embedding multi-line configuration inside a Java constant

Common mistakes

  • Single vs double quotes: Java uses double quotes for strings and single quotes for char. Don't swap them.
  • Forgetting to escape backslashes: "C:\Users" is invalid; use "C:\\Users" or a text block.
  • Copy-pasting from Word or Google Docs often inserts curly quotes (" ") that look right but aren't valid Java. Paste into a plain text editor first.
  • Line continuation in text blocks: use trailing \ (backslash) to join lines without a newline. Subtle but useful.