What is Char in Kotlin: Simple Explanation and Example
Char in Kotlin represents a single character, like a letter or symbol. It is a basic data type used to store one character enclosed in single quotes, such as 'A' or '7'.How It Works
Think of Char as a tiny box that can hold exactly one letter, number, or symbol. Just like you write a single letter on a sticky note, Char stores one character at a time. It is different from a word or sentence, which would be stored as a string.
In Kotlin, you write a Char by putting a single character inside single quotes, like 'K' or '!'. Behind the scenes, Kotlin uses a number code to remember which character it is, but you don’t need to worry about that when coding.
Example
This example shows how to create and print a Char in Kotlin.
fun main() {
val letter: Char = 'K'
val digit: Char = '7'
println("Letter: $letter")
println("Digit: $digit")
}When to Use
Use Char when you need to work with single characters, such as checking if a letter is uppercase, reading one character from user input, or processing text one character at a time. For example, if you want to count how many times the letter 'a' appears in a word, you would compare each Char in the word to 'a'.
It is also useful when you want to store symbols like punctuation marks or digits as characters rather than numbers.
Key Points
Charholds exactly one character.- Characters are written in single quotes, like
'A'. - It is different from
String, which holds multiple characters. - Useful for text processing and character checks.
Key Takeaways
Char stores a single character enclosed in single quotes.Char when working with individual letters, digits, or symbols.Char is different from String, which holds multiple characters.Char values easily in Kotlin.