You should use the StringEscapeUtils class from Apache Commons Text (you can also find the class in Apache Commons Lang3 but that one is deprecated). You'll find that there are plenty of other offerings in Apache Commons that might serve useful for other problems you have in Java development, so that you don't reinvent the wheel.

The specific call you want has to do with "Java escaping"; the API call is StringEscapeUtils.escapeJava(). For example:

System.out.println(StringEscapeUtils.escapeJava("Hello\r\n\tW\"o\"rld\n"));

would print out:

Hello\r\n\tW\"o\"rld\n

There are plenty of other escaping utilities in that library as well. You can find Apache Commons Text in Maven Central and you'd add it to your Maven project like this:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.3</version>
</dependency>

and in case you are using Gradle:

compile "org.apache.commons:commons-text:1.3"
Answer from schematic on Stack Overflow
Top answer
1 of 5
76

You should use the StringEscapeUtils class from Apache Commons Text (you can also find the class in Apache Commons Lang3 but that one is deprecated). You'll find that there are plenty of other offerings in Apache Commons that might serve useful for other problems you have in Java development, so that you don't reinvent the wheel.

The specific call you want has to do with "Java escaping"; the API call is StringEscapeUtils.escapeJava(). For example:

System.out.println(StringEscapeUtils.escapeJava("Hello\r\n\tW\"o\"rld\n"));

would print out:

Hello\r\n\tW\"o\"rld\n

There are plenty of other escaping utilities in that library as well. You can find Apache Commons Text in Maven Central and you'd add it to your Maven project like this:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.3</version>
</dependency>

and in case you are using Gradle:

compile "org.apache.commons:commons-text:1.3"
2 of 5
26

Many of the solutions here suggest adding the Apache Commons Text and using StringEscapeUtils. Some of the other solutions here are simply wrong.

A potential solutions is as follows:

/**
 * escape()
 *
 * Escape a give String to make it safe to be printed or stored.
 *
 * @param s The input String.
 * @return The output String.
 **/
public static String escape(String s){
  return s.replace("\\", "\\\\")
          .replace("\t", "\\t")
          .replace("\b", "\\b")
          .replace("\n", "\\n")
          .replace("\r", "\\r")
          .replace("\f", "\\f")
          .replace("\'", "\\'")      // <== not necessary
          .replace("\"", "\\\"");
}

The escape list is from Oracle's list. (Note that \\ is escaped first as you don't want to re-escape it later.)

This solution isn't as fast as it could be, but it should work. Ideally you would only parse the String once and you wouldn't need to keep rebuilding your String array. For small Strings this should be fine.

If you're thinking about this from the perspective of storing data, also consider something like converting it to Base64 representation - it's fast, single parse and uses not too much extra space.

🌐
FreeFormatter
freeformatter.com › java-dotnet-escape.html
Free Online Java or .Net Escape / Unescape Tool - FreeFormatter.com
Escapes or unescapes a Java or .Net string removing traces of offending characters that could prevent compiling.
People also ask

What are escape sequences in Java?

Escape sequences are special character combinations in Java, starting with a backslash (\), used to represent characters that cannot be typed directly (e.g., newline \n or tab \t).

🌐
iqratechnology.com
iqratechnology.com › academy › java › java-basic › java-escape-sequence-verbatim-string
Escape sequence & Verbatim String in Java
Why are escape sequences important in Java?

Escape sequences are essential for formatting Strings and including special characters in text, such as quotes, newlines, and tabs.

🌐
iqratechnology.com
iqratechnology.com › academy › java › java-basic › java-escape-sequence-verbatim-string
Escape sequence & Verbatim String in Java
Does the course provide examples of escape sequences?

Yes, the course includes practical examples to demonstrate each escape sequence.

🌐
iqratechnology.com
iqratechnology.com › academy › java › java-basic › java-escape-sequence-verbatim-string
Escape sequence & Verbatim String in Java
🌐
W3Schools
w3schools.com › java › java_strings_specchars.asp
Java Strings - Special Characters
Because strings must be written within quotes, Java will misunderstand this string, and generate an error: String txt = "We are the so-called "Vikings" from the north."; The solution to avoid this problem, is to use the backslash escape character.
🌐
CodeGym
codegym.cc › java blog › strings in java › java escape characters
Escaping characters in Java | CodeGym
In Java, a backslash combined with a character to be "escaped" is called a control sequence. For example, \" is a control sequence for displaying quotation marks on the screen. Upon encountering this construct in your code, the compiler will ...
Published   July 23, 2024
🌐
Shortc
shortc.com › java-escaper
Java String Escaper - Escape Online - Shortc
Escape Java strings online. Handles backslash sequences, unicode escapes, and surrogate pairs. 🔧🛠
🌐
JSON Formatter
jsonformatter.org › java-escape
Best Java Escape Characters tools to escape sequences and Strings
Escapes or unescapes a Java string removing traces of offending characters that could prevent compiling.
🌐
Shortc
javaescaper.com
Java String Escaper - Escape Online 🧰
Escape Java strings online. Handles backslash sequences, unicode escapes, and surrogate pairs. 🔧🛠
Find elsewhere
🌐
Avajava
avajava.com › tutorials › lessons › how-do-i-escape-a-string-for-java.html
How do I escape a String for Java?
This is our free web tutorial index that features a variety of topics related to Java web application development.
🌐
Iqra Technology
iqratechnology.com › academy › java › java-basic › java-escape-sequence-verbatim-string
Escape sequence & Verbatim String in Java
April 7, 2025 - Java does not have a direct equivalent of C#’s verbatim string (with @ ). However, you can avoid escape sequences by using triple quotes in newer versions (Java 13+) through text blocks .
🌐
GitHub
gist.github.com › awwsmm › b1707beead1adba391214b50fbd4a794
Notes on escape sequences in Java Strings · GitHub
# capture variable-width octal escape sequences like \02, \13, or \377 (?:[0-2][0-9]{1,2}|3[0-6][0-9]|37[0-7]|[0-9]{1,2}) |\\ # OR (get the preceding slash and)... u(?:[0-9a-fA-F]{4}) # capture fixed-width Unicode sequences like \u0242 or \uFFAD ) This captures the slash character at the beginning of all Java escape sequences listed in 3.
🌐
CodeSignal
codesignal.com › learn › courses › java-string-manipulation-for-beginners › lessons › escaping-into-java-mastering-special-character-sequences
Escaping into Java: Mastering Special Character Sequences
The output clearly illustrates how \" and \' help infuse strings with quotes! ... Great job! You've now mastered special character sequences in Java — newline (\n), tab (\t), backslash (\\), and quotes (\" and \'). With these in your toolkit, you will be able to perform many string manipulations for real-world programming scenarios.
🌐
Medium
medium.com › tuanhdotnet › escaping-strings-in-java-how-to-handle-special-characters-effectively-27a64747209f
Escaping Strings in Java: How to Handle Special Characters Effectively | by Anh Trần Tuấn | tuanhdotnet | Medium
February 1, 2025 - Escaping a string refers to the process of prefixing certain characters with a backslash () so that they are interpreted in a specific way by the Java compiler.
🌐
GeeksforGeeks
geeksforgeeks.org › java › escape-sequences-in-java
Escape Sequences in Java - GeeksforGeeks
Escape sequences in Java are used to represent special characters inside string and character literals.
Published   January 16, 2026
🌐
iO Flood
ioflood.com › blog › java-escape-characters
Java Escape Characters: Your Ultimate Guide
February 26, 2024 - To use escape characters in Java, you use a backslash (\) followed by the character you want to escape. For instance, to include a quotation mark within a string, you would write it as \”, such as: String example = "This is a \"quote\" inside ...
🌐
Baeldung
baeldung.com › home › json › escape json string in java
Escape JSON String in Java | Baeldung
January 8, 2024 - The simplest and smallest library in our review is JSON-java also known as org.json. To construct a JSON object, we simply create an instance of JSONObject and basically treat it like a Map: JSONObject jsonObject = new JSONObject(); jsonObject.put("message", "Hello \"World\""); String payload = jsonObject.toString(); This will take the quotes around “World” and escape them:
🌐
AlgoCademy
algocademy.com › link
Escaping Characters in Java | AlgoCademy
To include these characters in a string, we use the backslash (\) as an escape character. For example, to include a double quote inside a string, we use \" instead of just ". Similarly, to include a backslash, we use \\. This tells Java to treat ...
🌐
Oracle
docs.oracle.com › javase › tutorial › java › data › characters.html
Characters (The Java™ Tutorials > Learning the Java Language > Numbers and Strings)
The following table shows the Java escape sequences: When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence · She said "Hello!" to me. ... Copyright © 1995, 2024 Oracle and/or its affiliates. All rights reserved. Previous page: Questions and Exercises: Numbers Next page: Strings...
🌐
Baeldung
baeldung.com › home › java › core java › guide to escaping characters in java regexps
Guide to Escaping Characters in Java RegExps | Baeldung
July 22, 2024 - This means that in the previous example, we don’t want to let the pattern foo. to have a match in the input String. How would we handle a situation like this? The answer is that we need to escape the dot (.) character so that its special meaning is ignored. Let’s dig into it in more detail in the next section. According to the Java API documentation for regular expressions, there are two ways in which we can escape characters that have special meaning.
🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Escape special characters
If a query string is placed in an HREF attribute, then even a URL encoded query string is often not of valid form. This is because URLEncoder produces valid HTTP, but it doesn't in general produce text which is a valid HTML attribute - the ampersand character needs to be replaced by the corresponding character entity &amp;. Here is an example of a utility class which escapes special characters for HTML, XML, regular expressions, and so on. package hirondelle.web4j.util; import java.net.URLEncoder; import java.io.UnsupportedEncodingException; import java.text.CharacterIterator; import java.text
🌐
Zickty
zickty.com › javaescape
Java Escape Text Online Tool
Converts text containing special characters in Java to escape sequences. Java allows string literals to convert certain characters into escape sequences with characters used for structuring the code being mandatory to convert.