Course contentsShow
← Java
Lesson 2239 of 2,87043. String Handling in DepthFree lesson

Escape Sequences in Text Blocks

Use standard escape sequences like \n, \t, \", and \\ within text blocks for special characters and formatting.

Escape Sequences in Text Blocks

What You'll Learn

You'll learn how to use standard Java escape sequences like \n, \t, \", and \\ inside text blocks for special formatting and literal characters.

The Core Idea

Even though text blocks preserve most whitespace and newlines naturally, you still need escape sequences when you want precise control over formatting or when you need to include special characters that would otherwise be interpreted differently.

Text blocks support the same escape sequences you're already familiar with from regular strings:

  • \n — explicit newline (in addition to natural line breaks)
  • \t — tab character
  • \" — literal double quote (though usually not needed in text blocks)
  • \\ — literal backslash
  • \s — preserve a trailing space (text block-specific)
  • \ at end of line — line continuation without adding a newline

Why This Matters

Sometimes the natural formatting of a text block isn't enough. You might need an extra newline, a tab for alignment, or to preserve trailing spaces that would otherwise be stripped. Escape sequences give you that fine-grained control.

String formatted = """
        Name:\tJohn Doe
        Age:\t30
        
        Status:\tActive
        """;

Here, \t ensures consistent tab-based alignment that wouldn't be guaranteed with just spaces.

The Backslash-at-Line-End Trick

If you want text to appear on one line but write it across multiple lines in your code for readability:

String oneLine = """
        This is all \
        one continuous \
        line.""";

This produces: "This is all one continuous line."

Key Takeaway: Text blocks support all standard escape sequences, giving you precise control over formatting while maintaining the readability benefits of multi-line string literals.