char and Unicode in Java
char is a 16-bit UTF-16 code unit; char arithmetic and code points.
A char is a number in disguise
A char is a 16-bit UTF-16 code unit: a number from 0 to 65,535 that stands for a character. Because it's a number, you can do arithmetic with it.
int a = 'A'; // 65
int lower = 'a'; // 97
int zero = '0'; // 48, not 0!
int space = ' '; // 32Your turn
What does this print?
System.out.println('x' + 'y');xy241Compile error
Show the answer
Both chars are promoted to int: 120 + 121 = 241. + only joins text when one operand is a String: "" + 'x' + 'y' gives "xy".
++ keeps it a char
c + 1 produces an int. But c++ and c += 1 keep the variable a char: they include a hidden cast back to the variable's type, so the char moves to the next character.
char c = 'a';
c++;
System.out.println(c); // bWhen 16 bits aren't enough
Unicode has over a million possible code points (characters). Those above 65,535, like many emoji, don't fit in one char. UTF-16 stores them as two chars, called a surrogate pair. 😀 is code point U+1F600.
Your turn
Two letters and one emoji. What does length() say?
String s = "Hi😀";
System.out.println(s.length());346
Show the answer
4. H and i are one char each, but 😀 is a surrogate pair: two chars.
length() counts chars, not characters
length() counts chars (UTF-16 code units). To count real characters, use codePointCount or codePoints().
String s = "😀";
s.length() // 2
s.codePointCount(0, s.length()) // 1In real projects
Emoji break naive text code constantly. Cutting a message to 100 chars with substring can split a surrogate pair in half and show a broken symbol. Chat apps and username checks count code points instead.
Key takeaways
- 'A' is 65, 'a' is 97, '0' is 48
- char + int → int; char++ stays a char
- Emoji can take 2 chars: length() counts chars, not characters
- codePointCount / codePoints() count real characters
Java's char is 16 bits because, when Java was designed, all of Unicode fit in 16 bits. Unicode 2.0 (1996) grew beyond that, and Java 5 added code point methods to cope.
Practice questions
What does this print?
char c = 'a';
c++;
System.out.println(c);- 98
- b
- a1
- Compile error
Check your answer
b. ++ on a char variable keeps the type char, moving to the next code unit, 'b'. Increment operators include an implicit cast back to the variable's type.
What does this print?
System.out.println('a' + 'b');- ab
- 195
- a b
- Compile error
Check your answer
195. Both chars are promoted to int (97 + 98), so the result is 195. You need a String operand to get concatenation.