Data Types in Kotlin
📌 Data Types in Kotlin
In Kotlin, data types define the type of data that a variable can hold. Kotlin is a statically typed language, meaning the data type of variables is determined at compile time.
✅ 1. Basic Data Types in Kotlin
Kotlin provides the following built-in data types:
| Data Type | Size | Description | Example |
|---|---|---|---|
Byte | 8-bit | Stores small integers | val x: Byte = 10 |
Short | 16-bit | Stores larger integers | val x: Short = 100 |
Int | 32-bit | Stores whole numbers | val x: Int = 1000 |
Long | 64-bit | Stores large integers | val x: Long = 100000000L |
Float | 32-bit | Stores decimal numbers (Single Precision) | val x: Float = 10.5F |
Double | 64-bit | Stores decimal numbers (Double Precision) | val x: Double = 20.99 |
Char | 16-bit | Stores single characters | val x: Char = 'A' |
Boolean | 1-bit | Stores true or false values | val x: Boolean = true |
String | Variable | Stores text | val x: String = "Hello" |
✅ 2. Examples of Basic Data Types
fun () { val byteValue: Byte = 120 val shortValue: Short = 32000 val intValue: Int = 2147483647 val longValue: Long = 9223372036854775807L val floatValue: Float = 3.14F val doubleValue: Double = 3.14159265359 val charValue: Char = 'K' val booleanValue: Boolean = true val stringValue: String = "Kotlin Programming" println("Byte: $byteValue") println(val age = 25 // Inferred as Intval name = "John" // Inferred as Stringval isStudent = true // Inferred as Booleanprintln("Age: $age, Name: val num1: Int = 100val num2: Double = num1.toDouble()println("Int to Double: $num2")val num3: Int = str.toInt()println("String to Int: $num3")
Output:
Int to Double: 100.0String to Int: 123
✅ 5. Nullable Data Types
In Kotlin, variables are non-nullable by default.
If you want to allow a variable to store a null value, use a nullable data type by adding ?.
📌 Example: Nullable Data Types
var name: String? = "Alice"println(name?.length) // Safe call to prevent NullPointerExceptionname = nullprintln(name?.length) // Prints null
?.→ Safe call operator to avoidNullPointerException.
✅ 6. Conclusion
Kotlin provides all standard data types like
Int,Float,String, etc.Type inference reduces the need to specify data types explicitly.
Nullable types prevent null-related errors using
?and safe calls.Type conversion is done using functions like
toInt()andtoString().