Kotlin Arrays — Complete Guide

1. Why Use Arrays in Kotlin?

Arrays in Kotlin are used when you need to store a fixed number of elements of the same data type under a single variable name. Instead of creating multiple variables like num1, num2, num3, you can store them all in one array such as numbers.

Arrays make it easier to iterate, sort, and manipulate data efficiently — especially when the number of elements is known at compile time. They're memory efficient and provide direct index-based access.

Example:

// Without arrays
val num1 = 10
val num2 = 20
val num3 = 30

// With array
val numbers = arrayOf(10, 20, 30)
println(numbers[1]) // Output: 20
            

2. How to Declare and Use Arrays in Kotlin (with 5 Examples)

Example 1 — Using arrayOf()

// Basic declaration
val fruits = arrayOf("Apple", "Banana", "Cherry")

// Access elements
println(fruits[0])   // Apple
println(fruits.size) // 3

// Modify element
fruits[1] = "Mango"
println(fruits[1])   // Mango
        
Example 2 — Using Array() Constructor

// Create an array of 5 integers, each initialized as their index * 2
val numbers = Array(5) { i -> i * 2 }
println(numbers.joinToString()) // Output: 0, 2, 4, 6, 8
        
Example 3 — Using Typed Arrays (e.g., IntArray, DoubleArray)

// Type-specific array
val marks = intArrayOf(85, 90, 78, 92)
println(marks[2]) // Output: 78

// Modify value
marks[2] = 80
println(marks.joinToString()) // Output: 85, 90, 80, 92
        
Example 4 — Using arrayOfNulls()

// Create array with null values
val names = arrayOfNulls(3)
names[0] = "Talha"
names[1] = "Ali"
println(names.joinToString()) // Talha, Ali, null
        
Example 5 — Using list.toTypedArray()

// Convert List to Array
val list = listOf("A", "B", "C")
val arr = list.toTypedArray()

for (item in arr) println(item) // Prints A, B, C
        

3. When and When Not to Use Arrays?

✅ When to Use Arrays:
🚫 When Not to Use Arrays:

4. Top 10 Interview Questions on Arrays in Kotlin

  1. What is the difference between arrayOf() and Array() in Kotlin?
  2. How can you create an array of null elements in Kotlin?
  3. What’s the difference between Array<T> and IntArray?
  4. How do you iterate through an array in Kotlin?
  5. Can you store mixed types in a Kotlin array?
  6. How to convert a List to an Array and vice versa?
  7. What happens if you try to access an index outside the array bounds?
  8. How do you check if an element exists in an array?
  9. How to find the maximum or minimum element in an array?
  10. Can arrays in Kotlin be resized after initialization?
Bonus Tip 💡

In Kotlin, arrays are not dynamically resizable. If you need to add or remove elements frequently, prefer using MutableList instead.