Char Data type Usage and Type Conversion in Kotlin
On this page (9sections)
Definition
- Char data type is represented by single apostrophe just like Java in Kotlin.
- In JVM, the characteristics of this “Char” variable is derived from the characteristics of primitive type “char” of Java which has a non-nullable default value.
Syntax and declaration
A Char value can be declared by 3 ways as mentioned below.
1. Mentioning type explicitly
val variable_name : Char = 'v'
for example,
val name : Char = 'r'
2. Type is automatically inferred
val variable_name = 'v'
for example,
val name = 'r'
3. Declaring and Initializing separately
var variable_name : Char
variable_name = ''
for example
//Declaring and Initializing separately
var name:Char
name = 'r'
Char Data type Example Program in Kotlin
// Char Datatype Kotlin example program
// Data type Kotlin Programs, Basic Kotlin Programs
fun main(args:Array<String>) {
//Assigned value is inferred automatically by compiler
val name = 'm'
println("The character is: $c")
}
Sample Output
The character is: m
How It Works
This Kotlin program demonstrates Char Data type Usage and Type Conversion. It first prepares the data it needs, then performs the core operation step by step, and finally prints the output shown in the Sample Output above.
- Declare the variables that hold the program’s data.
- Print the final result to the console so you can compare it with the sample output.
Try changing the input values and re-running the program to see how the output changes — this is the fastest way to understand how the logic behaves.
Frequently Asked Questions
What is Char Data type Usage and Type Conversion in Kotlin?
Char data type is represented by single apostrophe just like Java in Kotlin.
How do I run this Kotlin example?
Run it in IntelliJ IDEA or Android Studio, or compile from the command line with `kotlinc file.kt -include-runtime -d file.jar` and run `java -jar file.jar`.
How can I practice Char Data type Usage and Type Conversion?
Copy the example into IntelliJ IDEA or Android Studio, run it, then change the values or add print statements to see how the output changes.