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

The Backslash-Newline Escape

Use \ at the end of a line to suppress the implicit newline, allowing logical continuation without line breaks.

The Backslash-Newline Escape

What you'll learn: How to suppress line breaks in text blocks using the backslash escape to control logical line continuation.

The Problem with Automatic Newlines

Text blocks automatically include a newline character at the end of each physical line you write. This is usually what you want for multi-line strings, but sometimes you need a logically long line that only appears broken in your source code for readability. That's where the backslash-newline escape comes in.

How the Backslash-Newline Escape Works

When you place a single backslash (\) at the very end of a line in a text block, Java suppresses the newline that would normally be added. The next line continues as if it were directly concatenated to the previous one, without any line break character in the resulting string.

Think of it like using a hyphen to split a word across lines in a book—the hyphen tells you the word continues on the next line without actually being part of the word itself.

String message = """
    This is a very long sentence that would be awkward \
    to read if it were all on one physical line in the \
    source code, but it will be one continuous line at runtime.
    """;

// Result: "This is a very long sentence that would be awkward to read if it were all on one physical line in the source code, but it will be one continuous line at runtime.\n"

Notice: there's only one newline in the result—at the very end. The backslashes removed the newlines after "awkward" and "the."

When to Use It

Use the backslash-newline escape when you want to keep your source code readable (by breaking long lines) without introducing actual line breaks into the string value itself. Common use cases include long sentences, URLs, or SQL queries where line breaks would cause problems.

Key Takeaway: The backslash at the end of a line (\) in a text block suppresses that line's newline, allowing you to logically continue the string on the next physical line without inserting a line break character.