0
0
Kotlinprogramming~5 mins

Array creation and usage in Kotlin

Choose your learning style9 modes available
Introduction

Arrays help you store many items together in one place. This makes it easy to keep and use groups of data.

When you want to keep a list of your favorite fruits.
When you need to store daily temperatures for a week.
When you want to remember scores of players in a game.
When you want to process a fixed number of items one by one.
Syntax
Kotlin
fun main() {
    // Create an array of integers
    val numbers: Array<Int> = arrayOf(1, 2, 3, 4, 5)

    // Access an element by index
    val firstNumber = numbers[0]

    // Change an element
    numbers[1] = 10

    // Print the array
    println(numbers.joinToString())
}

Arrays in Kotlin have fixed size once created.

Use square brackets [] to get or set an element by its position (index).

Examples
This shows how to create an empty array with no elements.
Kotlin
fun main() {
    // Empty array of Strings
    val emptyArray = arrayOf<String>()
    println(emptyArray.size) // 0
}
Array with only one item. Accessing index 0 gives that item.
Kotlin
fun main() {
    // Array with one element
    val singleElementArray = arrayOf("Hello")
    println(singleElementArray[0]) // Hello
}
Accessing the last element using size - 1 index.
Kotlin
fun main() {
    // Array with multiple elements
    val colors = arrayOf("Red", "Green", "Blue")
    println(colors[colors.size - 1]) // Blue
}
Sample Program

This program creates an array of names, changes one name, and prints the array before and after the change. It also prints the first name separately.

Kotlin
fun main() {
    // Create an array of names
    val names = arrayOf("Alice", "Bob", "Charlie")
    println("Before change: " + names.joinToString())

    // Change the second name
    names[1] = "Becky"
    println("After change: " + names.joinToString())

    // Access and print the first name
    val firstName = names[0]
    println("First name is: $firstName")
}
OutputSuccess
Important Notes

Accessing or changing an element by an invalid index causes an error.

Arrays have fixed size; to add or remove items, use other collections like lists.

Time complexity to access or change an element by index is O(1) - very fast.

Summary

Arrays store multiple items in one variable.

You can get or set items using their position (index).

Arrays have fixed size and fast access by index.