Write special characters in Java string literals
How to put quotes, backslashes, control characters, accented letters and emoji in Java strings: escape sequences, Unicode escapes, text blocks and their pitfalls.
Java offers several ways to put a character into a string literal: type it directly, use an escape sequence such as \n, use a Unicode escape such as \u00E9, or build the string at runtime from a code point. In most cases they all produce the same string value. What differs is how the source code reads, how well it survives copying and editing, and a few traps that only some approaches trigger. This guide explains each mechanism and when to use it.
Short answer: which approach suits which use
Use the standard escape sequences for double quotes, backslashes and control characters such as newlines and tabs. Type visible non-ASCII characters, such as é, ü or €, directly when your build fixes the source encoding to UTF-8. Use \uXXXX escapes for characters that are invisible or easy to confuse, such as non-breaking spaces, zero-width characters and bidirectional controls. Build characters above U+FFFF, such as most emoji, from a code point when readability matters. The tradeoff is consistent. Escapes make the source unambiguous and encoding-proof, but harder to read. Literal characters are easy to read but depend on every tool in the chain handling the file encoding correctly, and they can hide characters you cannot see.
What escaping changes, and what it does not
An escape is source notation only. The compiler converts it to the character it stands for, so the compiled string holds that character, not a backslash followed by letters. "caf\u00E9" and "café" compile to equal strings. Escaping changes the text stored in your .java file. It does not change the runtime value or how that value is displayed. Display is decided later by fonts, terminals and the output encoding.
| Escape | Produces | Notes |
| \n | Line feed (U+000A) | Standard newline |
| \r | Carriage return (U+000D) | |
| \t | Tab (U+0009) | |
| \b | Backspace (U+0008) | |
| \f | Form feed (U+000C) | |
| \s | Space (U+0020) | Java 15 and later; mainly used to keep trailing spaces in text blocks |
| " | Double quote | Required inside ordinary "..." literals |
| ' | Single quote | Required in char literals; optional in strings |
| \ | Backslash | Required for every literal backslash |
| \0 to \377 | Octal escape | Legacy form, limited to U+0000 through U+00FF |
| \ at end of line | Nothing (joins lines) | Text blocks only, Java 15 and later |
Unicode escapes are processed earlier than you might expect
The compiler translates \uXXXX before it splits source into tokens, and it does this everywhere, including inside comments. A Unicode escape therefore behaves exactly as if you had typed the character at that spot in the file. This leads to failures that ordinary escapes do not cause:
// Does not compile: \u000A becomes a real line break inside the literal
String broken = "line1\u000Aline2";
// Compiles: \n is a string escape, interpreted later
String ok = "line1\nline2";
// Does not compile: \u0022 is a real double quote, which ends the literal early
String quote = "\u0022";
// Also fails, even in a comment: \u followed by non-hex characters
// is an illegal Unicode escape, as in a path like C:\users
For line feeds, carriage returns, double quotes and backslashes, use the standard escapes (\n, \r, ", \), never their \u forms. A backslash starts a Unicode escape only when it is preceded by an even number of backslashes. So "\u0041" is a literal backslash followed by the text u0041, not the letter A.
Characters beyond U+FFFF: emoji and other supplementary characters
Java strings are sequences of UTF-16 code units, and a \u escape always takes exactly four hex digits. A character above U+FFFF therefore needs two escapes, called a surrogate pair. Java has no \U0001F600 or \x{...} syntax. If you would rather not work out surrogates by hand, build the character from its code point:
String face = "\uD83D\uDE00"; // U+1F600 as a surrogate pair
String same = new String(Character.toChars(0x1F600));
String also = Character.toString(0x1F600); // Java 11 and later
face.length(); // 2 (UTF-16 code units)
face.codePointCount(0, face.length()); // 1 (code point)
Many emoji that look like one symbol are really several code points. Flags combine regional indicator symbols. Family and profession emoji join several characters with ZERO WIDTH JOINER (U+200D). Skin tones add a modifier code point. For these, even codePointCount reports more than the single symbol a reader sees. To count or step through user-perceived characters, use java.text.BreakIterator.getCharacterInstance(). How well it handles newer emoji sequences depends on the JDK version, so test on the version you ship.
Combining marks and normalization
The same visible letter can be stored in more than one way. Two literals that look identical when rendered can still compare as unequal:
String precomposed = "\u00E9"; // é as a single code point
String combining = "e\u0301"; // e followed by COMBINING ACUTE ACCENT
precomposed.equals(combining); // false
Normalizer.normalize(combining, Normalizer.Form.NFC).equals(precomposed); // true
If you compare, look up or deduplicate strings that may come from different sources, normalize them first with java.text.Normalizer. The same structure matters if you transform the string afterwards. StringBuilder.reverse() is documented to keep surrogate pairs together, so a lone emoji such as U+1F600 survives reversal. However, it reverses combining marks and joined emoji sequences piece by piece. A reversed "e\u0301" puts the accent before the e, and the accent then attaches to whatever character precedes it.
Text blocks for multi-line content
Since Java 15, text blocks let you write multi-line strings with little escaping. Double quotes need no escape unless three appear in a row. Backslashes still need \. Indentation shared by all lines is removed, based on the least-indented line including the closing delimiter. Trailing spaces on each line are removed, which is what \s is for. Line endings are normalized to \n regardless of how the source file stores them.
String json = """
{
"name": "Ada",
"note": "trailing space kept:\s"
}
""";
String sentence = """
This is one long line \
split only in the source.""";
Backslashes in regular expressions and file paths
A regular expression in a string literal goes through two layers of escaping: first Java's, then the regex engine's. The regex \d+ is written "\d+", and matching one literal backslash takes four in the source. Windows paths have a quieter trap. "C:\temp\new" compiles without complaint but contains a tab and a line feed.
"C:\temp\new" // compiles, but holds a tab and a line feed
"C:\\temp\\new" // the intended path
Path.of("C:", "temp", "new") // avoids separators in literals entirely
Pattern.compile("\\d+"); // regex \d+
"a\\b".split("\\\\"); // splits on a single backslash
To match text literally instead of escaping it by hand, use Pattern.quote(). In replacement strings for replaceAll(), the characters $ and \ have special meaning. Matcher.quoteReplacement() escapes them for you.
Will the result stay readable and usable after copying or sharing?
Source encoding. Escapes are plain ASCII, so they pass unchanged through editors, diff tools, chat and email. Literal non-ASCII characters rely on every step reading and writing the file in the same encoding. If a file saved as Windows-1252 is compiled as UTF-8, or the reverse, you get garbled text or an "unmappable character" error. Since JDK 18 the platform default charset is UTF-8, and javac uses it unless told otherwise. On older JDKs the default depended on the operating system. Setting the encoding explicitly, with -encoding UTF-8 or the equivalent build-tool setting, removes the dependency.
Pasting from documents and web pages. Copied snippets can bring curly quotes, non-breaking spaces or zero-width characters with them. Curly quotes cannot delimit a Java literal, so the code fails to compile, which at least makes the problem visible. Invisible characters inside a literal compile silently, then break equals() checks or lookups later. When a string behaves oddly, print its code points with s.codePoints() to see what it actually contains.
Invisible and bidirectional characters. Bidirectional controls such as U+202E (RIGHT-TO-LEFT OVERRIDE) can make source display in an order that differs from how the compiler reads it. This technique has been publicized under the name Trojan Source. Writing such characters, along with U+200B and U+00A0, as \u escapes keeps them visible to reviewers. Where they are not needed, keep them out of source entirely.
Runtime output. Escaping has no effect on what a program prints. If output shows question marks or garbled characters, look at the output encoding, the console and the font, not the literal. On recent JDKs the stdout.encoding system property controls how System.out encodes text.
Search and editing. A search for é will not find \u00E9, and the reverse is also true, so search for both forms when auditing a codebase. Some editors and IDEs can display escapes as characters or convert between the two forms. Check what yours does instead of assuming either form is shown.
Accessibility. A screen reader reads an escape as its literal characters (backslash, u, digits), which is verbose but unambiguous. A literal symbol may be announced by name, by a generic placeholder, or not at all, depending on the screen reader and its punctuation settings. No screen reader testing supports a more specific claim here, so test with the assistive technology your team actually uses. For end users, accessibility depends on the runtime text, which is the same whichever form you write in source.
When plain text without escaping is the better choice
- Visible non-ASCII letters and symbols, in a project that enforces UTF-8 source encoding and where reviewers need to read the text.
- Multi-line prose, SQL, JSON or HTML, which read better in a text block than as a chain of \n and " escapes.
- User-facing messages that change or get translated, which belong in resource bundles rather than literals. Since Java 9, properties files loaded through ResourceBundle are read as UTF-8 by default, so they can hold characters directly.
- Text that non-developers edit, for whom escape sequences are an obstacle.
Using escaping tools and converters
Converters in IDEs, libraries and websites can turn text into an escaped Java literal. Before you rely on one, check four things in its output. Characters above U+FFFF should come out as surrogate pairs, not \U or \x forms that Java does not accept. Quotes and backslashes should be escaped. Line feeds should not be emitted as \u000A. Combining sequences should be left in the order you gave them. Apache Commons Text provides StringEscapeUtils.escapeJava() for doing this in code. For the opposite direction at runtime, String.translateEscapes() (Java 15 and later) interprets escape sequences in a string, but it does not process \u escapes. A web tool's appearance or marketing says nothing reliable about how it handles what you paste, so do not paste credentials or confidential text into a converter whose data handling you have not verified.
Limits of this guide
The behavior described here comes from the Java language rules and documented JDK APIs. No specific converter tool, IDE, terminal or screen reader was tested, so verify rendering and copy-paste behavior in the environments you actually use. Features tied to a version, including text blocks, \s, translateEscapes() and the UTF-8 default charset, are only available on the JDK versions noted above.