-
Numbers: These include integer types (
Byte
,Short
,Int
,Long
) and floating-point types (Float
,Double
). Floating-point values are denoted by a trailingf
forFloat
. -
Characters: This data type is used to store a single character. A character value must be enclosed in single quotes, e.g.,
'a'
,'b'
. - Boolean: This data type can hold only two values: true or false.
-
Array: An array is a mutable collection of a fixed number of elements, each identified by an index.
Arrays can be created using functions such as
arrayOf()
,intArrayOf()
,charArrayOf()
, etc. ThearrayOf()
function provides a quick and convenient way to create arrays of any data type. TheArray
class constructor can also be used to create arrays, which requires the size of the array and a lambda function to initialize elements. -
String: A String is a sequence of characters. For example,
"Kotlin tutorial at www.zyasin.com!"
. Strings are objects of theString
class.
In Kotlin, all data types are objects and can be categorized into the following types:
fun main() { // Declaring and assigning values to various number data types. val intNum: Int = 3 // Integer val shortNum: Short = 4000 // Short val longNum: Long = 13000000000L // Long val byteNum: Byte = 1 // Byte val doubleNum: Double = 3.99 // Double val floatNum: Float = 25.34f // Float // Print all declared numbers. println("Integer number type value is $intNum") println("Short number type value is $shortNum") println("Long number type value is $longNum") println("Byte number type value is $byteNum") println("Double number type value is $doubleNum") println("Float number type value is $floatNum") }
fun main() { // Declare and assign a letter to the character type. val letter: Char = 'K' // Print the declared character. println("Character letter is $letter") }
fun main() { // Declaring a boolean variable and assigning a value to it. val boolVariable: Boolean = true // Printing the boolean value. println("Boolean condition is $boolVariable") }
fun main() { // Declare an array of integers. val numbers = arrayOf(1, 2, 3, 4) // Explicit declaration with a specific type. val explicitNumbers = arrayOf(1, 2, 3, 4) // An array holding multiple different data types. val mixedArray = arrayOf(1.5, "www.zyasin.com/kotlin.html", 50, 'K') // Modify elements of the array. numbers[2] = 7 numbers.set(1, 8) // Access elements using indices. println(numbers[3]) // Prints the fourth element println(numbers.get(0)) // Prints the first element // Print the entire array. println(numbers.contentToString()) // Print the size of the array. println(numbers.size) }
fun main() { val text = "Kotlin tutorial at www.zyasin.com/kotlin.html" println(text[0]) // Prints the first character println(text[12]) // Prints the 13th character (index starts at 0) }
Quiz Questions
stringArrayOf()
?val numbers = arrayOf(1, 7, 3, 4)
. What happens when we try to use println(numbers[4])
?