AI Hints
Home›Java Tutorial›Comparing Strings, Escapes and Text Blocks, String.format
Java · Lesson 23 of 120

Escapes and Text Blocks

Special characters.

⏱ 2 min read▶ Video at 30:16🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

How do you put a quote mark inside a string, when quotes start and end the string? You use a backslash, called an escape.

  • Quotes inside quotes?
  • Use a backslash
  • Called escaping

Escape sequences

Backslash quote puts a quote mark inside the text. Backslash n starts a new line. Backslash t adds a tab. And two backslashes make one real backslash. Run it. The quotes appear, the text splits over two lines, and the folder path shows single backslashes.

Main.javajava
public class Main {
    public static void main(String[] args) {
        System.out.println("She said \"hi\"");
        System.out.println("Line one\nLine two");
        System.out.println("Name:\tSam");
        System.out.println("A folder: C:\\Users\\sam");
    }
}
Output
She said "hi"
Line one
Line two
Name:   Sam
A folder: C:\Users\sam

Text blocks

For text with many lines, Java has text blocks. Three double quotes start and end the block. Every line inside is kept, exactly as typed. Java removes the shared indentation on the left, but keeps extra spaces. Run it. The poem prints as it looks, with the second line indented. And it has four lines.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String poem = """
            Roses are red,
              violets are blue,
            Java has text blocks,
            and now you do too.
            """;
        System.out.print(poem);
        System.out.println(poem.lines().count() + " lines");
    }
}
Output
Roses are red,
  violets are blue,
Java has text blocks,
and now you do too.
4 lines

Escapes to remember

These four escapes cover almost everything. And for longer text, like a block of JSON, or SQL, text blocks are much easier to read.

keyvalue
\"a quote mark
\nnew line
\ttab
\\one backslash

Summary

Backslash escapes let you put quotes, new lines, and tabs in strings. Text blocks, with three quotes, hold many lines. Next, tidy output, with format.

Key takeaways
  • \" \n \t \\
  • """ text blocks """
  • Indentation removed
Next up: String.format — tidy output