Unicode and encodings
suggest changeText handling bugs usually come from mixing up three different things:
- characters as a human sees them ("é", "😀", "🇵🇱")
- Unicode code points: numbers assigned to characters, from
U+0000toU+10FFFF - bytes: how code points are stored in a file or sent over a network, as defined by an encoding such as UTF-8, UTF-16 or ISO-8859-1
Kotlin on the JVM stores a String as a sequence of UTF-16 code units. Each Char is a 16-bit value, not a full character. Code points above U+FFFF (most emoji, many CJK ideographs, historic scripts) take two Chars, called a surrogate pair.
This article shows how to count, iterate, encode, decode, normalize and compare Unicode text correctly. For string basics see String Literals and Elements of String.
length is not the number of characters
fun main() {
val s = "Zoë 😀"
println(s.length) // UTF-16 code units
println(s.codePointCount(0, s.length)) // code points
println(s.encodeToByteArray().size) // UTF-8 bytes
}
Output:
6
5
9
The emoji 😀 is code point U+1F600. It doesn't fit into 16 bits, so it is stored as two Chars (\uD83D\uDE00) and adds 2 to length. In UTF-8 it takes 4 bytes, and ë takes 2.
The same value can differ again from what a user perceives as "one character", as shown in the section on grapheme clusters below.
Char vs code point
A Char holds one UTF-16 code unit. Use Char.code to get its numeric value (the old toInt() is deprecated) and Char(code) to create one:
fun main() {
val c = 'é'
println(c.code) // 233
println("U+%04X".format(c.code))
println(Char(0x41)) // A
println('\u00E9' == c) // true
}
Output:
233
U+00E9
A
true
Kotlin escapes only support \uXXXX with exactly 4 hex digits. There is no \U0001F600 form, so a supplementary character must be written as the character itself, as a surrogate pair, or created from its code point at runtime:
fun main() {
val a = "😀"
val b = "\uD83D\uDE00" // surrogate pair
val c = Character.toString(0x1F600) // Java 11+
val d = buildString { appendCodePoint(0x1F600) }
val e = String(intArrayOf(0x1F600), 0, 1)
println(listOf(a, b, c, d, e).all { it == a })
println(Character.charCount(0x1F600)) // Chars needed for this code point
}
Output:
true
2
Iterating over code points
Iterating a string with for (c in s) yields Chars, which splits supplementary characters into two meaningless halves:
fun main() {
val s = "a😀"
for (c in s) {
println("'$c' U+%04X surrogate=%b".format(c.code, c.isSurrogate()))
}
}
Output:
'a' U+0061 surrogate=false
'?' U+D83D surrogate=true
'?' U+DE00 surrogate=true
A lone surrogate is not valid text, so the console prints ? (or �). To work with real code points use codePoints(), which returns a Java IntStream, or step through the string with codePointAt:
fun main() {
val s = "a😀é"
// 1. codePoints() stream
s.codePoints().forEach { cp ->
println("U+%04X %s".format(cp, Character.getName(cp)))
}
// 2. manual loop with index
var i = 0
while (i < s.length) {
val cp = s.codePointAt(i)
print(Character.toString(cp) + " ")
i += Character.charCount(cp)
}
println()
// 3. collect into a List<String>, one element per code point
val parts = s.codePoints().toArray().map { Character.toString(it) }
println(parts)
}
Output:
U+0061 LATIN SMALL LETTER A
U+1F600 GRINNING FACE
U+00E9 LATIN SMALL LETTER E WITH ACUTE
a 😀 é
[a, 😀, é]
Char predicates like isLetter() and isDigit() only see one code unit. For supplementary characters use the Character overloads that take an Int code point:
fun main() {
val gothicAhsa = "𐌰" // U+10330, a letter
println(gothicAhsa[0].isLetter()) // false: it's a surrogate
println(Character.isLetter(gothicAhsa.codePointAt(0))) // true
// Char predicates are Unicode-aware, not ASCII-only
println('٣'.isDigit()) // ARABIC-INDIC DIGIT THREE
println('٣'.digitToInt())
println('é'.category)
}
Output:
false
true
true
3
LOWERCASE_LETTER
Note that isDigit() accepts digits from all scripts. If you validate user input such as a PIN, check c in '0'..'9' instead.
Encoding: String to bytes
Converting a String to bytes always involves an encoding. encodeToByteArray() always uses UTF-8. toByteArray(charset) lets you choose; it also defaults to UTF-8 in Kotlin. Standard charsets are available as constants in kotlin.text.Charsets:
import java.nio.charset.Charset
fun ByteArray.hex() = joinToString(" ") { "%02X".format(it) }
fun main() {
val s = "€"
println("UTF-8: " + s.encodeToByteArray().hex())
println("UTF-16: " + s.toByteArray(Charsets.UTF_16).hex())
println("UTF-16LE: " + s.toByteArray(Charsets.UTF_16LE).hex())
println("UTF-32: " + s.toByteArray(Charsets.UTF_32).hex())
println("windows-1252: " + s.toByteArray(Charset.forName("windows-1252")).hex())
println("ISO-8859-1: " + s.toByteArray(Charsets.ISO_8859_1).hex())
println("US-ASCII: " + s.toByteArray(Charsets.US_ASCII).hex())
}
Output:
UTF-8: E2 82 AC
UTF-16: FE FF 20 AC
UTF-16LE: AC 20
UTF-32: 00 00 20 AC
windows-1252: 80
ISO-8859-1: 3F
US-ASCII: 3F
Things to notice:
UTF_16writes a byte order mark (FE FF) and uses big-endian.UTF_16LEandUTF_16BEwrite no BOM.€doesn't exist in ISO-8859-1 or ASCII.toByteArraysilently replaces unmappable characters with?(3F). That is data loss without an error.- windows-1252 is not the same as ISO-8859-1, even though they are often confused. They differ in the
0x80-0x9Frange.
Byte is signed in Kotlin, so 0xE2 is stored as -30. "%02X".format(byte) prints it as unsigned hex. When doing arithmetic, convert with b.toInt() and 0xFF.
To see how UTF-8 grows with the code point value:
fun ByteArray.hex() = joinToString(" ") { "%02X".format(it) }
fun main() {
for (s in listOf("A", "é", "€", "😀")) {
val cp = s.codePointAt(0)
val bytes = s.encodeToByteArray()
println("U+%05X %d byte(s) %s".format(cp, bytes.size, bytes.hex()))
}
}
Output:
U+00041 1 byte(s) 41
U+000E9 2 byte(s) C3 A9
U+020AC 3 byte(s) E2 82 AC
U+1F600 4 byte(s) F0 9F 98 80
ASCII is a subset of UTF-8, which is one reason UTF-8 is the default encoding for files, HTTP and JSON.
Decoding: bytes to String
Use decodeToString() for UTF-8, or String(bytes, charset) / bytes.toString(charset) for other encodings:
fun main() {
val utf8 = byteArrayOf(0x63, 0x61, 0x66, 0xC3.toByte(), 0xA9.toByte())
println(utf8.decodeToString())
val latin1 = byteArrayOf(0x63, 0x61, 0x66, 0xE9.toByte())
println(String(latin1, Charsets.ISO_8859_1))
println(latin1.toString(Charsets.ISO_8859_1))
}
Output:
café
café
café
Invalid input and replacement characters
By default, decoding never fails. Invalid byte sequences become U+FFFD REPLACEMENT CHARACTER (�). When you need to detect bad input, pass throwOnInvalidSequence = true:
import java.nio.charset.CharacterCodingException
fun main() {
val bad = byteArrayOf(0x48, 0x69, 0xFF.toByte(), 0x21)
val lenient = bad.decodeToString()
println(lenient)
println(lenient.contains('�'))
try {
bad.decodeToString(throwOnInvalidSequence = true)
} catch (e: CharacterCodingException) {
println("invalid UTF-8: ${e::class.simpleName}")
}
}
Output:
Hi�!
true
invalid UTF-8: MalformedInputException
For any charset, the same strict behavior is available through a CharsetDecoder:
import java.nio.ByteBuffer
import java.nio.charset.CharacterCodingException
import java.nio.charset.CodingErrorAction
fun decodeStrict(bytes: ByteArray, charset: java.nio.charset.Charset): String? =
try {
charset.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes))
.toString()
} catch (e: CharacterCodingException) {
null
}
fun main() {
println(decodeStrict("zażółć".encodeToByteArray(), Charsets.UTF_8))
println(decodeStrict(byteArrayOf(0xC3.toByte()), Charsets.UTF_8))
}
Output:
zażółć
null
Encoding has the same problem in the other direction. A string containing a lone surrogate (for example after cutting a string in the middle of a pair) is silently encoded as ?. encodeToByteArray(throwOnInvalidSequence = true) throws instead.
Mojibake
Decoding bytes with the wrong charset produces garbled text, known as mojibake. The classic case is UTF-8 bytes read as ISO-8859-1 or windows-1252:
fun main() {
val bytes = "café".encodeToByteArray() // 63 61 66 C3 A9
val wrong = String(bytes, Charsets.ISO_8859_1)
println(wrong)
// ISO-8859-1 maps every byte to one char, so this round trip is lossless
val fixed = String(wrong.toByteArray(Charsets.ISO_8859_1), Charsets.UTF_8)
println(fixed)
}
Output:
café
café
If you see é, € or ö in your output, some part of the pipeline decoded UTF-8 as a single-byte encoding. The repair trick above only works when no bytes were lost; the real fix is to specify the charset explicitly everywhere bytes become text.
Cutting strings safely
substring, take and [i] work on UTF-16 indices and can split a surrogate pair. Cutting a UTF-8 byte array can split a multi-byte sequence:
fun main() {
val s = "Zoë 😀!"
println(s.take(5)) // cuts the emoji in half
val bytes = s.encodeToByteArray()
println(String(bytes, 0, 7, Charsets.UTF_8)) // cuts inside a UTF-8 sequence
}
Output:
Zoë ?
Zoë �
A common real-world need is "truncate to at most N bytes of UTF-8" (database columns, HTTP headers, file names). Walk the string by code point and stop before going over the limit:
fun String.truncateToUtf8Bytes(maxBytes: Int): String {
var bytes = 0
var i = 0
while (i < length) {
val cp = codePointAt(i)
val n = when {
cp < 0x80 -> 1
cp < 0x800 -> 2
cp < 0x10000 -> 3
else -> 4
}
if (bytes + n > maxBytes) break
bytes += n
i += Character.charCount(cp)
}
return substring(0, i)
}
fun main() {
val s = "Zoë 😀!"
for (max in listOf(3, 7, 9, 100)) {
val t = s.truncateToUtf8Bytes(max)
println("$max -> '$t' (${t.encodeToByteArray().size} bytes)")
}
}
Output:
3 -> 'Zo' (2 bytes)
7 -> 'Zoë ' (5 bytes)
9 -> 'Zoë 😀' (9 bytes)
100 -> 'Zoë 😀!' (10 bytes)
This keeps code points intact. It can still separate a base letter from a combining accent; use grapheme boundaries (below) if that matters.
Grapheme clusters: what users call a character
A single visible character can consist of several code points:
éwritten ase+U+0301 COMBINING ACUTE ACCENT- the family emoji
👨👩👧: three emoji joined by twoU+200D ZERO WIDTH JOINER - the flag
🇵🇱: two regional indicator symbols
Unicode calls these extended grapheme clusters. Use java.text.BreakIterator to split text on them. Since JDK 20 it follows the Unicode rules for emoji sequences; older JDKs split emoji ZWJ sequences incorrectly.
import java.text.BreakIterator
fun String.graphemes(): List<String> {
val it = BreakIterator.getCharacterInstance()
it.setText(this)
val result = mutableListOf<String>()
var start = it.first()
var end = it.next()
while (end != BreakIterator.DONE) {
result += substring(start, end)
start = end
end = it.next()
}
return result
}
fun main() {
val s = "e\u0301👨👩👧🇵🇱"
println("length: ${s.length}")
println("code points: ${s.codePointCount(0, s.length)}")
val g = s.graphemes()
println("graphemes: ${g.size} $g")
}
Output (JDK 21):
length: 14
code points: 9
graphemes: 3 [é, 👨👩👧, 🇵🇱]
Use grapheme clusters when limiting the visible length of user input, moving a text cursor or reversing text. Note that reversed() keeps surrogate pairs together (it uses StringBuilder.reverse()), but it moves combining marks and joiners onto the wrong characters:
fun main() {
println("ae\u0301".reversed().codePoints().toArray().map { "U+%04X".format(it) })
}
Output:
[U+0301, U+0065, U+0061]
The accent now comes first and attaches to nothing. Reversing s.graphemes().reversed().joinToString("") gives the expected result.
Normalization
The same text can be encoded with different code point sequences. é can be one code point (U+00E9, precomposed) or two (e + U+0301, decomposed). They render identically but are not ==:
import java.text.Normalizer
fun main() {
val composed = "caf\u00E9"
val decomposed = "cafe\u0301"
println("$composed $decomposed")
println(composed == decomposed)
println("${composed.length} ${decomposed.length}")
val a = Normalizer.normalize(composed, Normalizer.Form.NFC)
val b = Normalizer.normalize(decomposed, Normalizer.Form.NFC)
println(a == b)
println(Normalizer.isNormalized(decomposed, Normalizer.Form.NFC))
// NFKC also folds "compatibility" characters
println(Normalizer.normalize("fi ① full", Normalizer.Form.NFKC))
}
Output:
café café
false
4 5
true
false
fi 1 full
The four forms are:
| Form | What it does | Typical use |
|---|---|---|
| NFC | compose where possible | storing and comparing text (most common) |
| NFD | fully decompose | stripping accents, some text processing |
| NFKC | compatibility fold + compose | identifiers, search, user names |
| NFKD | compatibility fold + decompose | search indexes |
macOS file systems and some input methods produce decomposed text, so normalize to NFC before comparing strings or using them as map keys.
Removing diacritics is a common use of NFD: decompose, then drop combining marks:
import java.text.Normalizer
fun String.stripAccents(): String =
Normalizer.normalize(this, Normalizer.Form.NFD)
.replace(Regex("\\p{M}+"), "")
fun main() {
println("Zażółć gęślą jaźń, Crème Brûlée".stripAccents())
}
Output:
Zazołc gesla jazn, Creme Brulee
ł has no decomposition in Unicode (it's a separate letter, not l + accent), so it is kept. Accent stripping is lossy and language specific; don't use it for anything but search and slugs.
Case conversion and comparison
uppercase() and lowercase() use Unicode rules with a locale-independent mapping (Locale.ROOT). The result can have a different length than the input:
import java.util.Locale
fun main() {
println("straße".uppercase()) // ß has no single uppercase form
println("fi".uppercase())
val turkish = Locale.forLanguageTag("tr")
println("istanbul".uppercase())
println("istanbul".uppercase(turkish)) // dotted capital İ
println("İ".lowercase().length) // i + combining dot above
println("STRASSE".equals("straße", ignoreCase = true))
}
Output:
STRASSE
FI
ISTANBUL
İSTANBUL
2
false
Always use the no-argument uppercase() / lowercase() for protocol keywords, identifiers and file extensions. The deprecated toUpperCase() used the default locale, which caused the infamous "Turkish i" bug where "title".toUpperCase() produced "TİTLE" on Turkish systems.
equals(ignoreCase = true) compares character by character, so it doesn't treat ß and SS as equal. For human-language comparison and sorting use java.text.Collator:
import java.text.Collator
import java.util.Locale
fun main() {
val words = listOf("zebra", "Äpfel", "apple", "Ångström", "banana")
println(words.sorted()) // by UTF-16 code unit value
val collator = Collator.getInstance(Locale.GERMAN)
println(words.sortedWith(collator))
}
Output:
[apple, banana, zebra, Äpfel, Ångström]
[Ångström, Äpfel, apple, banana, zebra]
Plain sorted() orders by numeric code unit values, so all accented capitals land after z. A collator compares base letters first (Å sorts like A, ignoring case and accents at the first level) and sorts the way people expect in a given language.
Files, streams and the default charset
Kotlin's File.readText(), File.writeText(), readLines(), bufferedReader() and friends default to UTF-8. Since Java 18 (JEP 400) the JVM's default charset is UTF-8 on every platform too, but code that must also run on older JVMs should still pass the charset explicitly:
import java.io.File
fun main() {
val f = File.createTempFile("enc", ".txt")
try {
val text = "Zoë 😀"
f.writeText(text) // UTF-8
println("UTF-8 file: ${f.length()} bytes")
f.writeText(text, Charsets.UTF_16LE)
println("UTF-16LE file: ${f.length()} bytes")
println(f.readText(Charsets.UTF_16LE))
// reading with the wrong charset doesn't fail, it produces garbage
println(f.readText(Charsets.UTF_8).length)
} finally {
f.delete()
}
}
Output:
UTF-8 file: 9 bytes
UTF-16LE file: 12 bytes
Zoë 😀
12
See Files and I/O for more about reading and writing files.
Byte order marks
Files saved by some Windows tools start with a UTF-8 BOM (EF BB BF). Java's UTF-8 decoder does not remove it, so the text starts with an invisible \uFEFF. That breaks header matching in CSV files, JSON parsing and startsWith checks:
import java.io.File
fun main() {
val f = File.createTempFile("bom", ".csv")
try {
f.writeBytes(byteArrayOf(0xEF.toByte(), 0xBB.toByte(), 0xBF.toByte()) +
"name,age\n".encodeToByteArray())
val text = f.readText()
println(text.startsWith("name"))
println("U+%04X".format(text[0].code))
val clean = text.removePrefix("\uFEFF")
println(clean.startsWith("name"))
} finally {
f.delete()
}
}
Output:
false
U+FEFF
true
Console output
When printed text looks garbled but the string is correct, the problem is usually the console. On Windows, older JVMs encoded System.out with the legacy console code page. Since Java 19 the encoding is taken from the stdout.encoding system property. If emoji or accented letters show up as ?, run with -Dstdout.encoding=UTF-8 and make sure the terminal itself uses UTF-8 (for example chcp 65001 in the classic Windows console).
Common mistakes
- Using
lengthas the number of characters. It counts UTF-16 code units. UsecodePointCountfor code points andBreakIteratorfor visible characters. - Iterating with
for (c in s)over text that may contain emoji. UsecodePoints(). - Calling
toByteArray()/String(bytes)without thinking about the charset. Name the charset whenever bytes come from or go to the outside world. - Assuming encoding errors throw. By default decoding inserts
�and encoding inserts?. UsethrowOnInvalidSequence = trueor aCharsetDecoderwithCodingErrorAction.REPORT. - Comparing strings from different sources without normalizing. Normalize to NFC first.
- Using
toUpperCase()/toLowerCase(). They are deprecated and locale dependent; useuppercase()/lowercase(). - Cutting UTF-8 byte arrays at arbitrary offsets. Truncate on code point (or grapheme) boundaries.
Summary
| Task | Code |
|---|---|
| UTF-16 length | s.length |
| number of code points | s.codePointCount(0, s.length) |
| iterate code points | s.codePoints().forEach { cp -> ... } |
| code point to string | Character.toString(cp) |
| char code | c.code, Char(65) |
| string to UTF-8 bytes | s.encodeToByteArray() |
| UTF-8 bytes to string | bytes.decodeToString() |
| other charsets | s.toByteArray(Charsets.UTF_16LE), String(bytes, Charsets.ISO_8859_1) |
| strict decoding | bytes.decodeToString(throwOnInvalidSequence = true) |
| normalize | Normalizer.normalize(s, Normalizer.Form.NFC) |
| visible characters | BreakIterator.getCharacterInstance() |
| locale-independent case | s.uppercase(), s.lowercase() |
| language-aware sorting | list.sortedWith(Collator.getInstance(locale)) |
| strip UTF-8 BOM | text.removePrefix("\uFEFF") |