An array stores a fixed number of values of the same type, one after another. You can read and change each value by its position (its index), but you can’t add or remove items once the array is created.
Page Contents
Creating arrays
fun main() {
val fruits = arrayOf("Apple", "Mango", "Banana")
val scores = intArrayOf(90, 75, 82)
val zeros = IntArray(4) // [0, 0, 0, 0]
val squares = IntArray(5) { it * it } // built from the index
println(fruits.joinToString())
println(scores.joinToString())
println(zeros.joinToString())
println(squares.joinToString())
}Output:
Apple, Mango, Banana 90, 75, 82 0, 0, 0, 0 0, 1, 4, 9, 16
println(fruits) would print something like [Ljava.lang.String;@1b6d3586, not the contents. Use joinToString() or contentToString() to print an array.
Primitive arrays
For numbers and other basic types, use the specialized arrays. They’re faster and use less memory than Array<Int>:
| Type | Create with |
|---|---|
IntArray | intArrayOf(1, 2) or IntArray(size) |
DoubleArray | doubleArrayOf(1.5) |
BooleanArray | booleanArrayOf(true) |
CharArray | charArrayOf('a') |
LongArray | longArrayOf(1L) |
Reading and changing elements
fun main() {
val marks = intArrayOf(45, 67, 89)
println(marks[0]) // first element
println(marks.last())
println(marks.size)
marks[1] = 70 // change an element
println(marks.contentToString())
println(marks.getOrNull(5)) // safe: null instead of a crash
}Output:
45 89 3 [45, 70, 89] null
Indexes run from 0 to size - 1. marks[3] here would crash with ArrayIndexOutOfBoundsException.
Looping over an array
fun main() {
val cities = arrayOf("Delhi", "Pune", "Jaipur")
for (city in cities) print("$city ")
println()
for (i in cities.indices) println("$i -> ${cities[i]}")
cities.forEachIndexed { i, c -> print("${i + 1}.$c ") }
println()
}Output:
Delhi Pune Jaipur 0 -> Delhi 1 -> Pune 2 -> Jaipur 1.Delhi 2.Pune 3.Jaipur
Useful functions
fun main() {
val nums = intArrayOf(42, 7, 19, 88, 3)
println(nums.sum())
println(nums.average())
println(nums.max())
println(nums.min())
println(nums.contains(19))
println(nums.indexOf(88))
println(nums.sorted()) // returns a List, array unchanged
nums.sort() // sorts the array itself
println(nums.contentToString())
println(nums.reversedArray().contentToString())
}Output:
159 31.8 88 3 true 3 [3, 7, 19, 42, 88] [3, 7, 19, 42, 88] [88, 42, 19, 7, 3]
Comparing arrays
== on two arrays checks whether they’re the same object, not whether they have the same contents. Use contentEquals:
fun main() {
val a = intArrayOf(1, 2, 3)
val b = intArrayOf(1, 2, 3)
println(a == b)
println(a.contentEquals(b))
}Output:
false true
2D arrays
fun main() {
val grid = Array(3) { row -> IntArray(3) { col -> row * 3 + col } }
for (row in grid) println(row.joinToString(" "))
println(grid[1][2])
}Output:
0 1 2 3 4 5 6 7 8 5
Array vs List
| Array | List | |
|---|---|---|
| Size | fixed | List fixed, MutableList can grow |
| Change elements | yes | only MutableList |
| Printing | needs contentToString() | prints nicely |
| Best for | performance-critical code, Java APIs, vararg | almost everything else |
In everyday Kotlin, lists are used far more often than arrays. You’ll learn them in the next lesson.
Converting
fun main() {
val arr = arrayOf("a", "b", "c")
val list = arr.toList()
val back = list.toTypedArray()
val ints = listOf(1, 2, 3).toIntArray()
println(list)
println(back.contentToString())
println(ints.sum())
}Output:
[a, b, c] [a, b, c] 6
Common mistakes
- Printing an array directly: use
contentToString(). - Comparing with
==: usecontentEquals(). - Index off by one: the last index is
size - 1. Preferindices,last()orgetOrNull().
Exercise
Given the temperatures of a week, print the hottest day, the average, and how many days were above 30°C.
fun main() {
val days = arrayOf("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
val temps = intArrayOf(31, 29, 34, 28, 33, 35, 30)
val hottest = temps.indices.maxBy { temps[it] }
println("Hottest: ${days[hottest]} (${temps[hottest]}°C)")
println("Average: ${"%.1f".format(temps.average())}°C")
println("Days above 30°C: ${temps.count { it > 30 }}")
}Output:
Hottest: Sat (35°C) Average: 31.4°C Days above 30°C: 4
FAQ
How do I create an array in Kotlin?
Use arrayOf("a", "b") for objects, intArrayOf(1, 2) for numbers, or IntArray(size) { … } to build one from its index.
How do I print an array in Kotlin?
println(arr.contentToString()) or println(arr.joinToString()).
Should I use an array or a list?
Use a List in most code. Use arrays when an API requires them or for performance-critical work with lots of numbers.
