Java String Escape & Unescape
Which characters are escaped?
| Character | Java escape | Meaning |
|---|---|---|
\ | \\ | Backslash |
" | \" | Double quote |
| newline | \n | Line feed (LF) |
| carriage return | \r | CR |
| tab | \t | Horizontal tab |
| backspace | \b | Backspace |
| form feed | \f | Form feed |
| any non-ASCII | \uXXXX | Unicode 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.
Related tools and guides
- JSON to Java POJO β generate classes from JSON
- XML to Java POJO β same for XML
- Base64 Encoder / Decoder β for binary data inside literals
- Java Online Compiler β test the escaped string
- String Length in Java β UTF-16 code units vs code points