Table of Contents
1. Escape Sequences in Java Strings
Java uses backslashes (\
) to escape characters with special meanings.
Common Escape Characters
Escape | Meaning | Example | Output |
---|---|---|---|
\n | Newline | "Line1\nLine2" | Line1 Line2 |
\t | Tab | "Name:\tAlice" | Name: Alice |
\" | Double Quote | "She said \"Hi\"" | She said “Hi” |
\\ | Backslash | "C:\\Users\\" | C:\Users\ |
\' | Single Quote | 'Don\'t stop' | Don’t stop |
Example:
String json = "{ \"name\": \"Alice\", \"age\": 30 }";
System.out.println(json);
// Output: { "name": "Alice", "age": 30 }
2. Unicode Characters
Java supports Unicode via \u
followed by a 4-digit hex code.
Using Unicode in Strings
String copyright = "Copyright \u00A9 2024"; // © symbol
String heart = "I \u2764 Java!"; // ❤ symbol
Key Notes:
- Unicode works for any character, including emojis:
\uD83D\uDE00
(😀). - Use hex values from Unicode charts.
3. Text Blocks (Java 15+)
Text blocks ("""
) simplify writing multi-line strings without escape characters.
Traditional vs. Text Block
// Old approach (messy):
String html = "<html>\n" +
" <body>\n" +
" <p>Hello</p>\n" +
" </body>\n" +
"</html>";
// Text block (clean):
String htmlBlock = """
<html>
<body>
<p>Hello</p>
</body>
</html>
""";
Text Block Rules
- Start/end with
"""
on separate lines. - Indentation is removed based on the closing
"""
position. - Escape
"""
inside with\"""
.
4. Handling Edge Cases
Escaping in Text Blocks
Use \
to suppress line breaks or escape delimiters:
String poem = """
Roses are red,\
Violets are blue.\
Java is awesome,\
And so are you!
""";
// Output: Roses are red, Violets are blue. Java is awesome, And so are you!
Mixing Quotes
Text blocks handle quotes without escaping:
String sql = """
SELECT * FROM users
WHERE name = "Alice"
""";
Common Mistakes
❌ Forgetting to Escape Backslashes:
String path = "C:\Users\file.txt"; // Error!
String path = "C:\\Users\\file.txt"; // ✅
❌ Incorrect Unicode Syntax:
String error = "\u00G1"; // Invalid hex 'G' → compile error
String correct = "\u00F1"; // ñ
❌ Text Block Alignment Issues:
// Misaligned closing """ adds unintended spaces:
String s = """
Hello
"""; // "Hello\n" (no trailing space)
FAQ
How to write a Windows file path without escaping?
Use text blocks (Java 15+) or replace \
with /
:
String path = """
C:\Users\Alice\file.txt
"""; // Backslashes allowed in text blocks!
Can I use text blocks for short strings?
Yes, but they’re best for multi-line content (JSON/HTML).
What Java versions support text blocks?
Standardized in Java 15 (preview in 13 and 14).