Kotlin Character Tutorial With Example

Kotlin character is represented by the type Char . For example, ‘D’, ‘F’, ‘9’ , ‘5’ etc.

How to declare and define a Kotlin Character ?

You can declare and define a character variable as

var firstChar: Char
firstChar = '9'

First line represents the character variable declaration in kotlin. Here, we have declared a character variable firstChar. Last line represents character variable definition in kotlin. In last line, we have assigned a value ‘9’ in character variable firstChar.

You can do declaration and definition in same line as below –

var char1: Char = 'F'

Here, we have declared and defined the variable in same line. We have assigned a value ‘F’ in character variable firstChar.

Mentioning data type Char is optional while declaring the character variable.
You can also declare and define the variable without mentioning the data type Char as below –

var firstChar = 'D'

Here, data type of the variable firstChar is decided by the assigned value ‘D’ . Since ‘D’ is of type character. So, data type of the variable firstChar is Character.

Key points to remember while using kotlin character

1. Kotlin Character can not be treated directly as numbers. Let’s take an example –

fun checkChar(c: Char) {
   if (c == 1) { // ERROR: incompatible types. You can not compare a character with a number
       // ...
   }
}

Note – You will get error because a character ‘c’ is being compared with a number 1 in the program.

2. We use single quote ‘ (e.g. ‘3’) to represent character literal. For example, ‘5’, ‘9’ , ‘s’ etc.
“S” is not a character but a string.

3. Special characters can be escaped using backslash. Following escape sequences are supported by default –

\t, \b, \n, \r, \', \", \\ and \$

4. To encode any other character, use escape sequence syntax ‘\uFF00’. A Sample program to convert a character in kotlin into Integer –

fun main(args: Array<String>) {
   var num = decimalDigitValue('9')
   print(num)
}

fun decimalDigitValue(c: Char): Int {
   if (c !in '0'..'9')
       throw IllegalArgumentException("Out of range")
   return c.toInt() - '0'.toInt() // Explicit conversions to numbers
}

Output –
9

Note – In this function only acceptable parameters are ‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’ . Any other value will result into ‘Out of range’ output.

Exercises on Kotlin character

1. Guess the output of below program –

fun main(args: Array<String>) {
   var firstChar: Char
   print(firstChar)
}

2. Guess the output of below program –

fun main(args: Array<String>) {
       var firstChar = 'SS'
       print(firstChar)
}

3. Guess the output of below program –

fun main(args: Array<String>) {
   var c = '9'
   if (c == 9) {
       print("C is equal to 9")
   } else {
       print("C is not equal to 9")
   }
}

4. Guess the output of below program –

fun main(args: Array<String>) {
    var c = '9'
   print(c)
}

That’s end of tutorial on Kotlin Character.

Leave a Reply