Sub topic 6
Characters: char and Unicode
Java’s char type stores a small piece of text. You can use it for a letter grade, a punctuation mark, or a symbol. But a char does not always hold a whole visible character, so it helps to understand how Java stores text.
A char value
A char variable holds one value written between single quotes:
char grade = 'A';
char digit = '7';
char mark = '?';The value '7' is a character, not the whole number 7. The quotes matter: 'A' is a char value, while "A" is a String value. A String is Java’s type for text made from zero or more pieces.
Some char values use an escape sequence. An escape sequence is a way to write a special value using a backslash.
| char value | Meaning |
|---|---|
| 'A' | The letter A |
| '\n' | A new line |
| '\'' | A single quote |
| '\u03A9' | The Greek capital letter Omega: Ω |
The last example uses a Unicode escape. The four digits after the u are a hexadecimal number, a number written with digits 0–9 and letters A–F.
Unicode and UTF-16
Unicode is a standard that assigns numbers to characters from many writing systems. Each of those numbers is called a code point. For example, the code point for A is written as U+0041.
Java stores a char as one 16-bit UTF-16 code unit. UTF-16 is a way to represent Unicode text as pieces called code units. A bit is a small unit of stored information.
Many characters, including A and Ω, fit in one code unit. But some code points, including many emoji, need two code units. Those two units are called a surrogate pair. A single char cannot hold the entire pair.
Even a character that looks like one symbol can sometimes contain more than one code point. For text that may contain such characters, use a String rather than assuming one char is enough.
Try it
Save this program as CharacterExample.java:
class CharacterExample {
public static void main(String[] args) {
char letter = 'A';
char symbol = '\u03A9';
char quote = '\'';
String face = "\uD83D\uDE00";
System.out.println("Letter: " + letter);
System.out.println("Symbol: " + symbol);
System.out.println("Quote: " + quote);
System.out.println("Face: " + face);
System.out.println("UTF-16 units: " + face.length());
System.out.println(
"Code points: " + face.codePointCount(0, face.length())
);
}
}Compile and run it:
javac CharacterExample.java
java CharacterExampleA terminal that supports these symbols should show:
Letter: A
Symbol: Ω
Quote: '
Face: 😀
UTF-16 units: 2
Code points: 1The face String contains a surrogate pair. Its length is two UTF-16 code units, but those units represent one code point. The codePointCount call counts from the start of the String to its end.
Exercise
Why can 'A' be stored in one char, while the emoji 😀 needs a String with two UTF-16 code units?
Show answer
A fits in one UTF-16 code unit. The emoji’s code point needs a surrogate pair, so one char is not enough.