Course contentsShow
← Java
Lesson 61 of 2,8702. Variables and Primitive TypesFree lesson

String Literals and Escape Characters

Write string literals with double quotes and use escape sequences within strings.

String Literals and Escape Characters

You'll learn how to write text values in Java and include special characters that can't be typed directly.

What is a String Literal?

A string literal is how you write text directly in your code. In Java, you enclose any text in double quotes ("), and that becomes a string value you can use in your program—like when you printed "Hello World" using System.out.println.

System.out.println("This is a string literal");

The Problem: Special Characters

What if you need to include a double quote inside your text, or start a new line? You can't just type another " because Java thinks you're ending the string! This is where escape characters come in.

An escape sequence starts with a backslash (\) and tells Java "treat the next character specially." Think of the backslash as saying "wait, don't interpret this normally."

Common Escape Sequences

  • \" — puts a double quote in your string
  • \\ — puts a single backslash in your string
  • \n — creates a new line (like pressing Enter)
  • \t — creates a tab space
System.out.println("She said, \"Hello!\"");        // She said, "Hello!"
System.out.println("Line one\nLine two");          // Two separate lines
System.out.println("Column1\tColumn2");            // Tab-separated
System.out.println("C:\\Users\\Documents");        // C:\Users\Documents

Notice how \" lets you include quotes in the output, and \n splits the text across lines even though it's one string literal in your code.

Key Takeaway: Use double quotes to create string literals, and use escape sequences (backslash + character) to include special characters like quotes, newlines, or backslashes themselves.