Characters
The Char type represents a single character as a UTF-16 code unit.
Use Char for individual character values, such as letters, digits, punctuation marks, or whitespace. For sequences of characters, use String.
Syntax
To declare a character, enclose the value in single quotes (' '). You can specify the Char type explicitly or let Kotlin infer it from the value:
A character literal must contain exactly one character. Otherwise, the Kotlin compiler reports an error:
Nullable values
To store a nullable value, use Char?:
Unicode support
Kotlin represents Char values as UTF-16 code units. This means that a single Char stores one UTF-16 code unit, not necessarily one complete Unicode character.
Basic Multilingual Plane
A single Char can store values in the range from \u0000 to \uFFFF. This range covers the Basic Multilingual Plane (BMP) that includes characters for almost all modern languages and a large number of symbols.
To specify a character by the Unicode value, use \u followed by four-digit hexadecimal value from the Unicode table:
Supplementary characters
Unicode characters outside the BMP, such as emojis and some historic scripts, cannot be represented by a single Char. In UTF-16, they are encoded as a surrogate pair, where two Char values together represent one Unicode character in a String:
Escape sequences
Use escape sequences for special characters that are difficult to write directly in source code or have a special meaning.
Every escape sequence begins with a backslash (\).
Supported sequence | Description |
|---|---|
| Tab |
| Backspace |
| New Line (LF) |
| Carriage Return (CR) |
| Single quotation mark |
| Double quotation mark |
| Backslash |
| Dollar sign |
For example:
Operations
Char supports comparison, inspection, case conversion, and explicit numeric conversion.
Character comparison
To compare Char values, use standard comparison operators such as ==, !=, <, >, <=, and >=.
Kotlin compares Char values by their numeric Unicode values and returns a Boolean value:
Character processing
Kotlin provides functions for inspection and case conversion of character values. For example:
Character arithmetic
You can create another character value by adding or subtracting an integer:
You can also use the increment (++) and decrement (--) operators in the prefix and postfix forms with mutable variables:
Character conversion
To convert Char to a numeric type, use explicit conversion:
Use
.codeto get the numeric Unicode value of a character:fun main() { //sampleStart val letter = 'A' println(letter.code) // 65 //sampleEnd }If a character represents a decimal digit, use
digitToInt():fun main() { //sampleStart val digit = '7' println(digit.digitToInt()) // 7 //sampleEnd }