Why escape text in Java?
Escaping text in Java is necessary when you want to include special characters in string literals. Java uses backslashes (\) as escape characters to represent characters that would otherwise be difficult or impossible to include directly in a string.
Examples of Java String Escaping
Original Java code
String message = "Hello "World"!";
char newline = '
';
String path = "C:\Program Files\Java";
String json = "{"name": "John", "age": 30}";
// Tab character: and backspace:
String unicode = "© Copyright Symbol";Escaped text
String message = \"Hello \"World\"!\";\nchar newline = \'\n\';\nString path = \"C:\\Program Files\\Java\";\nString json = \"{\"name\": \"John\", \"age\": 30}\";\n// Tab character: \t and backspace: \nString unicode = \"© Copyright Symbol\";Common Java Escape Sequences
| Escape Sequence | Character | Description |
|---|---|---|
| \" | " | Double quote |
| \' | ' | Single quote |
| \\ | \ | Backslash |
| \n | New line | Line feed |
| \r | Carriage return | Carriage return |
| \t | Tab | Horizontal tab |
| \b | Backspace | Backspace character |
| \f | Form feed | Form feed character |
| \uXXXX | Unicode character | Unicode character (e.g., \u00A9 for ©) |
When to Use Java String Escaping
- When including special characters in string literals
- When working with file paths (especially on Windows where backslashes are used)
- When creating strings that contain quotes or other characters that have special meaning in Java
- When including control characters like tabs or newlines in strings
- When working with regular expressions (which have their own escaping rules)
Tip:
In Java, you can also use raw string literals (introduced in Java 15) for strings with many special characters. Raw string literals are enclosed in triple quotes (""") and don't require escaping most characters.
Related Tools
- Unescape Java - Convert escaped Java strings back to their original form
- Escape JavaScript - Escape text for use in JavaScript
- Escape C# - Escape text for use in C# string literals
- Escape JSON - Escape text for use in JSON
- Escape HTML - Escape text for use in HTML
All Tools
See all available tools