← Chapter 3 — Strings, Escapes & Math

14. Escape Sequences

mixed

Description

Escape sequences represent characters that are hard to type directly inside a String. They begin with a backslash.

Use escapes to add new lines, tabs, quotation marks, or a literal backslash. This is especially useful for formatted messages and file paths.

Subtopics

Line breaks and tabs

Description

\n starts a new line and \t inserts a tab.

Explanation

They are interpreted inside a quoted Java string.

Example

System.out.println("Name\tScore\nAditi\t92");

Quotes and backslashes

Description

Escape quote and backslash characters.

Explanation

A backslash changes the meaning of the character after it.

Example

String quote = "She said \"Great!\"";

Explanation

Do not confuse the two-character text \n with an actual line break. Java interprets it as a line break only inside a String or character literal.

Example

public class EscapeDemo {
    public static void main(String[] args) {
        System.out.println("Student\tGrade");
        System.out.println("Aditi\tA");
    }
}

Key points

  • \n creates a new line.
  • \t inserts a tab.
  • \" places a quote inside text.

Open reference