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

Character Literals and Escape Sequences

Understand single-quoted character literals and escape sequences like \n, \t, \', \", and \\.

Character Literals and Escape Sequences

You'll learn how to write single characters in Java code, including special characters that need escape sequences.

What Are Character Literals?

A character literal is a single character enclosed in single quotes ('). This tells Java you're defining a char value. For example, 'A', '7', or '$' are all character literals. Remember: single quotes for char, not double quotes (those are for something different you'll learn later).

The Problem with Special Characters

Some characters can't be typed directly in your code—like a new line or a tab. Others have special meaning in Java syntax, like the single quote itself. How do you include these in a char variable?

Enter Escape Sequences

An escape sequence is a backslash (\) followed by a special character code. Think of the backslash as saying "treat the next character differently." Here are the essential ones:

  • '\n' — newline (moves to the next line)
  • '\t' — tab (horizontal spacing)
  • '\'' — single quote character (otherwise Java thinks the quote ends the literal)
  • '\"' — double quote character
  • '\\' — backslash itself (since \ starts an escape sequence)

Simple Examples

char newline = '\n';      // represents a line break
char tab = '\t';          // represents a tab space
char quote = '\'';        // the actual ' character
char backslash = '\\';    // the actual \ character

Think of escape sequences like keyboard shortcuts—special combinations that produce characters you can't easily type or see.

Key Takeaway: Use single quotes for character literals, and escape sequences (starting with \) to represent special characters like newlines, tabs, quotes, and backslashes.