Character Literals and Escape Sequences
What you'll learn: How to write single characters in Java code, including special characters that can't be typed directly.
Using Single Quotes for char Literals
In Java, you represent a single character by enclosing it in single quotes. This tells the compiler you're creating a char value:
char letter = 'A';
char digit = '7';
char symbol = '$';
Notice the single quotes ('), not double quotes. Double quotes are for something else you'll learn later.
Escape Sequences: Special Characters
But what if you need a character that's invisible or has special meaning? Like a new line or a tab? You can't just press Enter inside the quotes! That's where escape sequences come in—special two-character codes that start with a backslash (\):
char newline = '\n'; // moves to next line
char tab = '\t'; // horizontal tab spacing
char backslash = '\\'; // the backslash itself
char singleQuote = '\''; // the single quote character
Think of the backslash as saying "the next character is special—interpret it differently."
Common Escape Sequences
\n— newline (like pressing Enter)\t— tab (like pressing Tab)\\— a literal backslash\'— a single quote (needed because quotes normally end the literal)\"— a double quote
Unicode Escapes
You can also use \u followed by four hexadecimal digits to represent any Unicode character:
char heart = '\u2764'; // ❤
This gives you access to every character in the Unicode standard.
Key Takeaway: Use single quotes for char literals, and escape sequences like \n, \t, and \uXXXX let you represent special and Unicode characters that can't be typed directly.