Java escape for string literals
The Java escape tool prepares text for a "…" string literal in Java source code. It produces the same style of output as Apache Commons Text’s StringEscapeUtils.escapeJava(): readable ASCII stays readable, and everything that could upset the compiler or a non-UTF-8 build is escaped.
Escaping rules
\→\\and"→\".- Line feed, carriage return, tab, backspace and form feed →
\n,\r,\t,\b,\f. - Any other control character and every non-ASCII character →
\uXXXX. Characters above U+FFFF, like emoji, become a UTF-16 surrogate pair. - The single quote is left alone: it needs escaping only in a
charliteral ('\''), not in a string.
Example
Input:
Path "C:\data"
naïve 🚀 it'sOutput:
Path \"C:\\data\"\nna\u00EFve \uD83D\uDE80 it's
Why non-ASCII is escaped
Java source files are only compiled correctly if javac reads them with the right encoding. Before Java 18 the default depended on the platform, so a literal é could turn into é on a Windows build server. Writing \u00E9 is pure ASCII and compiles identically everywhere, which is why many style guides and .properties files use it.
Java strings versus .properties files
Escaped text often ends up in a .properties file rather than in source code, and the rules there are close but not identical:
- Encoding.
Properties.load(InputStream)still reads files as ISO-8859-1, so non-ASCII characters must be written as\uXXXX, exactly as this tool produces them. Resource bundles have been read as UTF-8 since Java 9, but the\uform works in both cases. - Quotes. A properties value is not wrapped in quotes, so the escaped
\"is unnecessary there (it still loads as a plain quote). - Keys. In keys,
=,:and spaces must be escaped with a backslash, and a line starting with#or!is a comment. Those rules do not apply to Java string literals.
To inspect a finished properties file as structured data, try Properties to JSON.
A Java-only pitfall: \u in comments
The Java compiler translates \uXXXX sequences before it tokenises the file. That means \u000A is a real line break even inside a comment or string, and "\u0022" closes the string. This tool therefore always uses \n, \" and friends for special characters and never emits a Unicode escape that could change the structure of your code.
Text blocks
Since Java 15 you can also write multi-line strings as text blocks ("""), where line breaks and quotes need no escaping. The escaped single-line form from this tool remains useful for annotations, older Java versions, generated code and constants.
In code, Apache Commons Text provides StringEscapeUtils.escapeJava() (the older Commons Lang version is deprecated), and code generators such as JavaPoet escape literals automatically. Use this tool when you are writing constants, test data or annotation values by hand.
Decode escaped strings with Java Unescape, or format a whole class with the Java Formatter. For C# code, see .NET (C#) Escape. Everything runs in your browser.