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

Trailing Whitespace Handling

Learn how trailing whitespace on each line is removed by default and how to preserve it using escape sequences.

Trailing Whitespace Handling

What you'll learn: How Java text blocks automatically strip trailing whitespace from each line and how to preserve it when needed.

The Default Behavior

When you use text blocks in Java, the compiler silently removes all trailing whitespace characters (spaces, tabs) from the end of each line before the string is created. This default behavior keeps your string data clean and prevents accidental whitespace pollution that's invisible in your source code.

Think of it like an auto-trim feature that runs on every line individually—Java assumes you don't want those trailing spaces you can't see when reading your code.

Why This Matters

Trailing whitespace is usually unintentional. A developer might accidentally leave spaces at the end of a line, and without automatic removal, these invisible characters would become part of your string data, potentially causing bugs in output formatting, tests, or data processing.

String poem = """
    Roses are red    
    Violets are blue
    """;
// The spaces after "red" are automatically removed

Preserving Trailing Whitespace

Sometimes you do need trailing whitespace—perhaps for fixed-width formatting or specific output requirements. Use the \s escape sequence to mark each trailing space you want to keep:

String formatted = """
    Name:    \s\s\s
    Age:     \s\s\s
    """;
// Each \s becomes a space that survives the trimming process

The \s escape tells Java: "This whitespace is essential, not incidental—keep it."

Key Takeaway: Text blocks strip trailing whitespace from each line by default to prevent invisible character bugs; use \s escape sequences to explicitly preserve any trailing spaces you actually need.