The char Type: Representing Single Characters
You'll learn how Java stores individual characters like letters, digits, and symbols using the char primitive type.
What is char?
The char type is Java's way of representing a single character. Think of it as a container that holds exactly one letter, digit, punctuation mark, or symbol. Unlike the integer types you've learned (int, long, short, byte), char is specifically designed for text characters.
How char Works
Java uses 16-bit Unicode to store characters, which means each char can represent over 65,000 different symbols—from English letters to Chinese characters, emojis, and mathematical symbols. This 16-bit size gives char enough room to handle characters from almost any written language.
Declaring char Variables
You declare a char variable just like the numeric types you've seen, but you assign character literals enclosed in single quotes:
char initial = 'J';
char digit = '7';
char symbol = '$';
char space = ' ';
Notice the single quotes ('A')—they're required for character literals. Each variable holds exactly one character.
Important Details
- Single quotes only:
'A'is achar, but"A"(double quotes) is something different you'll learn later. - One character:
'AB'won't work—charholds only a single character. - Unicode values: Behind the scenes, each character is stored as a number from 0 to 65,535.
Key Takeaway: The char type stores single characters using 16-bit Unicode, declared with single-quote literals like 'A' or '9', enabling Java to work with text from any language.