Video in progress
What does this code print: why does length() differ from the byte count?
String s = "oʻzbek"; // ʻ is U+02BB, not a plain apostrophe
System.out.println(s.length());
System.out.println(s.getBytes(StandardCharsets.UTF_8).length);
It prints 6 and 7. length() counts UTF-16 code units, which is 6 characters. In UTF-8, plain Latin letters take 1 byte, but the ʻ (U+02BB) character from the official Uzbek orthography takes 2 bytes. The number of characters and the number of bytes are not always equal.
📖 Answer
UTF-8 is a variable-length encoding:
- ASCII (Latin letters, digits): 1 byte;
- Cyrillic, Arabic and many other alphabets: 2 bytes;
- Chinese characters and many symbols: 3 bytes;
- emoji: 4 bytes.
Let's count "oʻzbek": o, z, b, e, k take 1 byte each, and ʻ takes 2 bytes. 5 + 2 = 7. In an interview people rush here and say "6 and 6". Cyrillic letters also take 2 bytes each in UTF-8, and € takes 3 bytes.
Where it matters in practice:
- a
VARCHAR(n)column is measured in bytes in some databases: a 100-character Cyrillic text might not fit; - the HTTP
Content-Lengthis in bytes, notlength(); - if you cut text at a byte boundary, you split a letter in the middle.
An emoji has one more trap: for a single emoji length() returns 2 (a surrogate pair). For the real number of characters use s.codePointCount(0, s.length()).
Sign up to mark studied questions and save your progress.