☕ Java

Escape Sequences

Escape sequences are special character combinations beginning with a backslash that represent characters which cannot be typed directly in a string or character literal — such as newlines, tabs, quotes, and the backslash itself. Java processes escape sequences at compile time, replacing each sequence with its corresponding character value before the program runs.

Complete Escape Sequence Reference

Java defines eight standard escape sequences plus unicode escapes. Each begins with a backslash followed by one or more characters. The compiler replaces every escape sequence with the single character it represents before storing the string. Using an unrecognised escape sequence (such as \p) is a compile error.
Java
// ── All Java escape sequences: ───────────────────────────────────────
//
//  Sequence   Name                 Unicode   Decimal
//  ─────────  ───────────────────  ────────  ───────
//  	         Horizontal tab       	    9
//  
         Newline (line feed)  
    10
//  
         Carriage return      
    13
//           Form feed                12
//           Backspace                8
//  '         Single quote         '    39
//  "         Double quote         "    34
//  \         Backslash            \    92
//  \0–\377    Octal escape         varies    0255


// ── Demonstrating each escape sequence: ──────────────────────────────
System.out.println("Tab:	here");           // Tab:    here
System.out.println("Line
Break");          // Line
                                            // Break
System.out.println("Backspace");          // Bacspace  (deletes 'k' visually)
System.out.println("Formfeed");           // Form (page break — rarely visible)
System.out.println("Carriage
Return");     // Return (cursor to line start)
System.out.println("Single 'quote'");     // Single 'quote'
System.out.println("Double "quote"");     // Double "quote"
System.out.println("Back\slash");          // Backslash

// ── Char literals also use escape sequences: ──────────────────────────
char tab        = '	';
char newline    = '
';
char singleQuote = ''';
char backslash  = '\';

System.out.println("Tab char value: " + (int) tab);       // 9
System.out.println("Newline value:  " + (int) newline);   // 10

// ── Unrecognised escape — compile error: ──────────────────────────────
// String s = "hello p world";   // ERROR: illegal escape character
// String s = "C:path	oile";  // ERROR: p and 	 interpreted

// ── Correct file paths on Windows: ────────────────────────────────────
String path1 = "C:\Users\Alice\Documents\file.txt";  // doubled backslash
String path2 = "C:/Users/Alice/Documents/file.txt";      // forward slash also works
System.out.println(path1);   // C:UsersAliceDocumentsile.txt

Newline and Tab in Detail

The newline (\n) and tab (\t) escape sequences are by far the most commonly used. Newline moves the output cursor to the beginning of the next line. Tab moves the cursor to the next tab stop (every 8 characters by default in most terminals). Understanding the difference between \n and %n in printf is important — %n uses the platform-specific line separator while \n always uses the Unix line feed character.
Java
// ── 
 — newline inside a string: ───────────────────────────────────
String address = "123 Main Street
" +
                 "Springfield
" +
                 "IL 62701";
System.out.println(address);
// Output:
// 123 Main Street
// Springfield
// IL 62701

// ── Multiple 
 — create blank lines: ────────────────────────────────
System.out.println("Section 1

Section 2");
// Output:
// Section 1
//              ← blank line
// Section 2

// ── 	 — tab alignment: ───────────────────────────────────────────────
System.out.println("Name		Score	Grade");
System.out.println("Alice		95	A");
System.out.println("Bob		87	B");
System.out.println("Charlie		72	C");
// Output (approximate — tab stops vary by environment):
// Name            Score   Grade
// Alice           95      A
// Bob             87      B
// Charlie         72      C
// NOTE: use printf() for reliable column alignment — tabs are not
// consistent across terminals.

// ── 
 vs %n vs System.lineSeparator(): ──────────────────────────────
System.out.printf("Line 1
Line 2%n");
// 
  → always Unix LF  (char 10)       — fine for most uses
// %n  → System.lineSeparator()          — platform-specific (CRLF on Windows)
// Use %n in printf for files written on Windows.
// Use 
 for console output (fine on all platforms).

String ls = System.lineSeparator(); // "
" on Linux/Mac, "
" on Windows
System.out.println("Cross-platform" + ls + "newline");

Quotes and Backslash

Double quotes must be escaped inside string literals because an unescaped double quote ends the string. Single quotes must be escaped inside char literals. Backslashes must be doubled because a single backslash starts an escape sequence — this is particularly important in file paths, regular expressions, and format strings.
Java
// ── Double quote inside a String: ────────────────────────────────────
String quote   = "She said "Hello!"";
String jsonStr = "{"name": "Alice", "age": 30}";
String html    = "<a href="https://example.com">Link</a>";

System.out.println(quote);    // She said "Hello!"
System.out.println(jsonStr);  // {"name": "Alice", "age": 30}
System.out.println(html);     // <a href="https://example.com">Link</a>

// ── Single quote in char literal: ────────────────────────────────────
char apostrophe = ''';
System.out.println("Char: " + apostrophe);   // Char: '

// Single quote does NOT need escaping inside a String:
String possessive = "Alice's book";          // fine — no escape needed
System.out.println(possessive);              // Alice's book

// ── Backslash — must be doubled everywhere: ───────────────────────────
String winPath  = "C:\Program Files\Java\bin";
String regexSep = "\s+";          // regex for one or more whitespace chars
String regexDig = "\d{3}-\d{4}"; // regex for phone number pattern

System.out.println(winPath);    // C:Program FilesJavain
System.out.println(regexSep);   // s+
System.out.println(regexDig);   // d{3}-d{4}

// ── Backslash in regex — four backslashes for literal : ───────────────
// To match a literal backslash with regex:
// - String needs "\\" (4 chars → 2 actual backslashes)
// - Regex engine sees "\" (1 escaped backslash = match literal )
String text    = "C:\Users\Alice";
String escaped = text.replaceAll("\\", "/");
System.out.println(escaped);    // C:/Users/Alice

// ── Java 15+ Text Blocks — avoid most escaping: ──────────────────────
String json = """
        {
            "name": "Alice",
            "age": 30,
            "city": "London"
        }
        """;
System.out.println(json);
// No escaped quotes needed — text block handles it.

Unicode Escape Sequences

Unicode escape sequences (\uXXXX) represent any Unicode character using its four-hex-digit code point. Unlike other escape sequences which are processed at the string-parsing stage, Unicode escapes are processed even earlier — at the lexical translation phase — meaning they can appear anywhere in source code including identifiers and comments, which leads to some surprising behaviour.
Java
// ── Unicode escape syntax: \uXXXX (four hex digits): ─────────────────
char   omega   = 'Ω';    // Ω — Greek capital omega
char   heart   = '♥';    // ♥ — black heart suit
char   euro    = '€';    // € — euro sign
char   snowman = '☃';    // ☃ — snowman

System.out.println("Omega: "   + omega);    // Omega: Ω
System.out.println("Heart: "   + heart);    // Heart: ♥
System.out.println("Euro: "    + euro);     // Euro: €
System.out.println("Snowman: " + snowman);  // Snowman: ☃

// ── Unicode in strings: ───────────────────────────────────────────────
String greeting  = "你好";          // 你好 — Mandarin "Hello"
String copyright = "Copyright © 2025"; // Copyright © 2025
String trademark = "Java™";            // Java™

System.out.println(greeting);              // 你好
System.out.println(copyright);            // Copyright © 2025
System.out.println(trademark);            // Java™

// ── Unicode processed at lexical phase — can appear in identifiers: ───
int café = 42;    // valid! é = é — identifier is "café"
System.out.println(café);   // 42

// ── Surprising behaviour — Unicode in comments: ───────────────────────
// 
 is a newline — this comment "ends" at 
 even in comments
// The following would cause a compile error if 
 appeared mid-comment:
// int x = 1; // set x
x = 2; ← 
 is a real newline here

// ── Unicode for supplementary characters (code points > U+FFFF): ──────
// Characters above U+FFFF require surrogate pairs or String.codePointAt:
String emoji = "😀";    // 😀 — grinning face (U+1F600)
System.out.println(emoji);        // 😀
System.out.println("Length: " + emoji.length());      // 2 (two chars)
System.out.println("Code points: " +
    emoji.codePointCount(0, emoji.length()));          // 1 (one symbol)

// ── Octal escapes (legacy — avoid in new code): ───────────────────────
char octalA   = '\101';   // 'A' (octal 101 = decimal 65)
char octalZ   = '\132';   // 'Z' (octal 132 = decimal 90)
char maxOctal = '\377';   // highest octal escape = 255 decimal
System.out.println("Octal A: " + octalA);   // A
// Prefer \uXXXX over octal — clearer and more portable.

Text Blocks and Escape Sequences (Java 15+)

Text blocks (introduced in Java 15) are multi-line string literals delimited by triple double quotes. They automatically handle indentation stripping and do not require escaping double quotes, making them ideal for JSON, HTML, SQL, and regex patterns. Text blocks support two new escape sequences — \s (force trailing space) and \ (suppress newline) — in addition to all standard escape sequences.
Java
// ── Text block syntax: ──────────────────────────────────────────────
//  String name = """
//          content here
//          more content
//          """;
//
//  Opening """ must be followed by a newline.
//  Closing """ position determines indentation stripping.

// ── No escaping needed for double quotes: ─────────────────────────────
String json = """
        {
            "service": "order-service",
            "version": "2.1.0",
            "active": true
        }
        """;
System.out.println(json);
// Output:
// {
//     "service": "order-service",
//     "version": "2.1.0",
//     "active": true
// }

// ── HTML without escaped quotes: ─────────────────────────────────────
String html = """
        <html>
            <body>
                <h1>Hello, "World"!</h1>
                <p class="intro">Welcome.</p>
            </body>
        </html>
        """;

// ── SQL queries — much cleaner than concatenation: ────────────────────
String sql = """
        SELECT u.id, u.name, o.total
        FROM   users u
        JOIN   orders o ON o.user_id = u.id
        WHERE  u.active = true
          AND  o.total > 100.00
        ORDER  BY o.total DESC
        """;

// ── New escape sequences in text blocks: ─────────────────────────────

// s — explicit space (prevents trailing whitespace stripping):
String columns = """
        Alice   s
        Bob     s
        Charlie s
        """;
// The s ensures the trailing spaces are preserved.

//   (backslash + newline) — line continuation (suppress newline): ────
String longLine = """
        This is a very long string that         continues on the next source line         but has no newlines in the output.
        """;
System.out.println(longLine);
// Output: This is a very long string that continues on the next source
//         line but has no newlines in the output.

// ── Standard escape sequences still work in text blocks: ─────────────
String mixed = """
        Line 1	Tabbed
        Line 2	Tabbed
        """;
System.out.print(mixed);
// Output:
// Line 1  Tabbed
// Line 2  Tabbed