Kotlin Chars

A Char represents a single character — one letter, one digit, one symbol, or one special character. Unlike a String which can hold any amount of text, a Char always holds exactly one character.

Declaring a Char

val letter: Char = 'A'
val digit: Char  = '5'
val symbol: Char = '@'
val space: Char  = ' '

Char values always use single quotes. Double quotes create a String, not a Char.

val correct: Char   = 'K'      // Char
val wrong: String   = "K"      // String (not a Char!)

Char and Unicode

Every Char is backed by a Unicode number. Unicode assigns a unique number to every character in every human language. Kotlin uses these numbers internally.


'A' → Unicode value 65
'B' → Unicode value 66
'Z' → Unicode value 90
'a' → Unicode value 97
'0' → Unicode value 48
val ch = 'A'
println(ch.code)          // 65 (Unicode number)

val fromCode = 66.toChar()
println(fromCode)         // B

Char Arithmetic

Because Chars have numeric Unicode values, you can do arithmetic on them:

val c = 'A'

println(c + 1)       // B (A is 65, 65+1=66='B')
println(c + 4)       // E
println('Z' - 'A')   // 25 (number of steps from A to Z)

Char Comparisons

println('A' < 'B')    // true  (65 < 66)
println('z' > 'a')    // true  (122 > 97)
println('0' == '0')   // true
println('A' == 'a')   // false (different Unicode values)

Checking Char Properties

val ch = 'K'

println(ch.isLetter())       // true
println(ch.isDigit())        // false
println(ch.isUpperCase())    // true
println(ch.isLowerCase())    // false
println(ch.isWhitespace())   // false

val digit = '7'
println(digit.isDigit())     // true
println(digit.digitToInt())  // 7 (converts char to its number)

Char Case Conversion

val upper = 'G'
val lower = 'g'

println(upper.lowercaseChar())   // g
println(lower.uppercaseChar())   // G

Char in a String

A String is made of Chars placed in sequence. You can access individual Chars from a String using the index position:


String: "Kotlin"
Index:   0 1 2 3 4 5

'K' at index 0
'o' at index 1
't' at index 2
'l' at index 3
'i' at index 4
'n' at index 5
val word = "Kotlin"

for (ch in word) {
    print("$ch ")
}
// Output: K o t l i n

Char Escape Sequences

val newline:   Char = '\n'   // moves to next line
val tab:       Char = '\t'   // horizontal tab
val backslash: Char = '\\'   // backslash character
val singleQ:   Char = '\''   // single quote inside a Char

Practical Example: Vowel Checker

fun main() {
    val letters = listOf('a', 'e', 'k', 'o', 't', 'u', 'i')
    val vowels = setOf('a', 'e', 'i', 'o', 'u')

    for (ch in letters) {
        val type = if (ch in vowels) "vowel" else "consonant"
        println("'$ch' is a $type")
    }
}

Output:

'a' is a vowel
'e' is a vowel
'k' is a consonant
'o' is a vowel
't' is a consonant
'u' is a vowel
'i' is a vowel

Leave a Comment

Your email address will not be published. Required fields are marked *