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

The \s Escape: Preserving Trailing Spaces

Learn the \s escape sequence to explicitly preserve trailing whitespace that would otherwise be stripped.

The \s Escape: Preserving Trailing Spaces

You'll learn how to use the \s escape sequence to explicitly keep trailing whitespace that text blocks would otherwise strip away.

The Problem: Text Blocks Strip Trailing Spaces

As you learned in the previous lesson on trailing whitespace handling, text blocks automatically remove spaces at the end of each line. This is usually convenient, but sometimes you genuinely need those trailing spaces—for example, when formatting fixed-width output or preserving exact formatting from configuration files.

The \s Escape Sequence

Java provides the \s escape sequence specifically to mark spaces that should survive the stripping process. Think of \s as a "protected space"—it tells the compiler "I really mean this space, don't remove it."

Each \s represents one space character that will be preserved, even at the end of a line.

How It Works

String withoutEscape = """
    Hello   
    World   
    """;
// Trailing spaces are stripped: "Hello\nWorld\n"

String withEscape = """
    Hello\s\s\s
    World\s\s\s
    """;
// Trailing spaces preserved: "Hello   \nWorld   \n"

You can also mix \s with regular spaces:

String mixed = """
    Name:     John\s\s
    Address:  123 Main St\s\s
    """;
// The spaces before \s are preserved as part of essential whitespace
// The \s spaces are explicitly preserved as trailing spaces

When to Use It

Use \s when you need trailing whitespace for:

  • Fixed-width formatted output (reports, tables)
  • Preserving exact spacing in templates
  • Matching legacy file formats with specific spacing requirements

Key Takeaway: Use \s to explicitly preserve trailing spaces in text blocks that would otherwise be automatically stripped—each \s guarantees one space character survives.