Video lecture
Watch on YouTube(opens in a new tab)Sub topic 6
Characters: char and Unicode
What is a char?
A char is a Java primitive type used to store one unit of text. You can use it for a letter, digit, symbol, or other text unit.
For example, char grade = 'A'; declares a variable named grade and gives it the value A. The single quotes tell Java that 'A' is a char value.
A char is different from a String. A String is a Java reference type used to hold text, such as a word or sentence. Strings use double quotes:
'A'is achar."A"is aString, even though it contains only one letter."Hello"is aStringcontaining several letters.
This distinction matters because a char and a String are different types. You cannot replace the single quotes in a char declaration with double quotes and expect the same result.
Unicode and UTF-16
Unicode is a standard for representing text from many languages and writing systems. It gives text symbols numbers called code points. For example:
Ahas the code pointU+0041.éhas the code pointU+00E9.😀has the code pointU+1F600.
The U+ notation shows a Unicode code point. The digits after it use hexadecimal, a number system that uses 0 through 9 and A through F.
Java represents text using UTF-16. UTF-16 is a way to represent Unicode text as units of 16 bits. A bit is a unit of information that can be 0 or 1.
A Java char holds one UTF-16 unit. For many characters, one unit is enough. For some characters, UTF-16 needs two units. This means that a char does not always hold a whole character that a person sees on screen.
Writing char values
A char literal is a char value written directly in Java code. Put it inside single quotes, as in 'A', '7', or '?'. The value '7' is a text character, not the whole number 7.
Some values need an escape sequence. An escape sequence uses a backslash to write a value that would be hard to type or that has a special meaning in code.
| Literal | Meaning |
|---|---|
| `'A'` | The letter A |
| `'7'` | The digit character 7 |
| `'\n'` | A line break |
| `'\''` | A single quote |
| `'\\'` | A backslash |
| `'\u00E9'` | The character é |
The last example is a Unicode escape. In Java, \u followed by four hexadecimal digits describes one UTF-16 unit. The escape '\u00E9' therefore gives a char the value é.
You can also write 'é' directly if your source file uses an encoding that supports it. A source file’s encoding is the way its text is stored as bytes. The Unicode escape is useful when you want the value to be clear even without typing the symbol itself.
A char literal must represent exactly one UTF-16 unit. For example, 'AB' and '' are not valid char literals. A character that needs two UTF-16 units, such as 😀, cannot fit in a single char either.
Characters that need two units
When a Unicode character needs two UTF-16 units, those units form a surrogate pair. The first is called a high surrogate, and the second is called a low surrogate. Together, they represent one code point.
For example, 😀 has the code point U+1F600. In UTF-16, it uses the units \uD83D and \uDE00. A String can hold both units, but one char cannot.
Java also permits a char or String to contain a surrogate without its matching partner. Such a unit is not a complete representation of a character by itself. This is one reason to be careful when taking individual char values from text.
Worked example
This program creates two char variables and a String containing a smiling face. It then checks a letter and looks at the string’s UTF-16 units and code point.
Save the program as CharacterExample.java:
class CharacterExample {
public static void main(String[] args) {
char letter = 'A';
char accent = '\u00E9';
String smile = "\uD83D\uDE00";
System.out.println("Letter: " + letter);
System.out.println("Accent: " + accent);
System.out.println("Is the letter a letter? "
+ Character.isLetter(letter));
System.out.println("Smile: " + smile);
System.out.println("UTF-16 units: " + smile.length());
System.out.println("First unit is a high surrogate: "
+ Character.isHighSurrogate(smile.charAt(0)));
System.out.println("Code points: "
+ smile.codePointCount(0, smile.length()));
System.out.println("First code point as a number: "
+ smile.codePointAt(0));
}
}In a terminal, run:
javac CharacterExample.java
java CharacterExampleYou should see:
Letter: A
Accent: é
Is the letter a letter? true
Smile: 😀
UTF-16 units: 2
First unit is a high surrogate: true
Code points: 1
First code point as a number: 128512Your terminal may show a replacement symbol for é or 😀 if it cannot display those characters. The counts can still be correct.
Reading the results
A method is a named action that a program can call. This example uses several Java methods:
Character.isLetter(letter)checks whether thecharvalue is a letter. Here it returnstrue.smile.length()counts UTF-16 units in the string. It returns2, not1.smile.charAt(0)gets the first UTF-16 unit as achar. The0is an index: a position in the string, counting from zero.Character.isHighSurrogate(...)checks whether that first unit is a high surrogate. It returnstrue.smile.codePointCount(0, smile.length())counts code points from the start of the string up to its end. It returns1for this pair.smile.codePointAt(0)reads the code point starting at index0. It returns a number of typeint.
The number 128512 is the decimal form of U+1F600. Decimal is the familiar number system that uses digits 0 through 9.
The example shows why counting char values is not always the same as counting code points. It also shows why looking at just smile.charAt(0) does not give you the whole smiling face.
Code points and visible characters
Even a code point count is not always the same as the number of characters a reader sees.
For example, text can represent an accented letter as a regular letter followed by a separate accent mark. Those are two code points, but they can appear as one visible character. Some emoji also use several code points to make one visible symbol.
Use a char when you know that one UTF-16 unit is enough for the value you need. If you are working with general text, use a String and take care when counting or examining its contents.
Practice
Exercise
What is the difference between 'A' and "A" in Java?
Show answer
'A' is a char value. "A" is a String containing one UTF-16 unit.
Exercise
A String contains only the smiling face represented by "\uD83D\uDE00". What do its length and code point count return?
Show answer
Its length is 2 UTF-16 units. Its code point count is 1.
Exercise
Write a char declaration for a line break. Why not use '\u000A'?
Show answer
Write char breakChar = '\n';. Java processes \u000A as a line break before reading the rest of the code, so it cannot be used that way inside the literal.