Kotlin example

How to declare and initialize an array in Kotlin

8 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

List the values in arrayOf: val names = arrayOf("Ada", "Grace") gives an Array<String>, Java's String[]. For numbers use intArrayOf(1, 2, 3), which gives an IntArray (Java's int[]). For a size without values, write IntArray(5) (five zeros) or Array(5) { i -> i * i }. Print an array with contentToString(), never on its own.

Kotlin has no new int[] and no {1, 2, 3} initializer. Arrays are a class, Array<T>, plus one class per primitive type (IntArray, DoubleArray, BooleanArray and so on), and you create them with functions: arrayOf and intArrayOf for known values, constructors with a size and an optional lambda for the rest. The sections below cover those, the difference between IntArray and Array<Int>, empty arrays, 2D arrays, and when a List is the better pick, then a table to choose from. Each example runs on this page: hit Run, then edit the code and run it again.

1arrayOf() and intArrayOf(): an array with valuesRecommended

When you know the values, pass them to arrayOf. Kotlin infers the element type and sets the size from the count. For primitive numbers, intArrayOf, doubleArrayOf, longArrayOf and friends build the primitive array types. When the values alone don't say the type you want, give it in angle brackets: arrayOf<Number>(1, 2.5, 3L). Elements are read and written by index from 0; the size is fixed once the array exists. Printing an array directly doesn't show its elements, so every example here uses contentToString() or joinToString().

ArrayOf.kt
fun main() {
    // arrayOf infers the type from the values: Array<String>
    val names = arrayOf("Ada", "Grace", "Linus")
    // Primitive arrays have their own builders: IntArray, DoubleArray, ...
    val scores = intArrayOf(90, 75, 82)
    // Spell out the type when the values don't say it
    val mixed = arrayOf<Number>(1, 2.5, 3L)

    // Printing an array directly shows an address, so use these
    println(names.contentToString())
    println(scores.joinToString())
    println(mixed.joinToString(" | "))

    // Read and write by index; size is fixed
    println("first: ${names[0]}, last: ${names.last()}, size: ${names.size}")
    names[1] = "Margaret"
    scores[2] += 10
    println(names.contentToString())
    println(scores.contentToString())

    // Indexes outside 0 until size throw
    try {
        println(names[3])
    } catch (e: ArrayIndexOutOfBoundsException) {
        println(e.message)
    }
    println(names.getOrNull(3))
}

Output

contentToString() prints [Ada, Grace, Linus], and joinToString() gives 90, 75, 82 with a separator you can change. A plain println(names) prints something like [Ljava.lang.String;@6bc7c054: the JVM type name and a hash code, not your data. A val array can still change its elements, so names[1] = "Margaret" and scores[2] += 10 compile; val only stops you from pointing names at another array. Reading index 3 of a 3-element array throws ArrayIndexOutOfBoundsException with Index 3 out of bounds for length 3, while getOrNull(3) returns null.

2IntArray vs Array<Int>, and Java’s String[]

The two look alike and are not the same type. IntArray compiles to Java's int[]: a block of plain numbers. Array<Int> compiles to Integer[]: an array of boxed Integer objects, which costs more memory and time. Note that arrayOf(1, 2, 3) gives the boxed Array<Int>; you need intArrayOf for the primitive one. Use the primitive types for numbers unless you need null elements or an API asks for Array<Int>. For objects there is only one form: Array<String> is Java's String[], which is why main can take args: Array<String>.

IntArrayVsArray.kt
fun total(values: IntArray): Int = values.sum()

fun main() {
    // IntArray is Java's int[]: primitives, no boxing
    val primitive: IntArray = intArrayOf(1, 2, 3)
    // Array<Int> is Java's Integer[]: each element is a boxed object
    val boxed: Array<Int> = arrayOf(1, 2, 3)

    println(primitive::class.java.simpleName)
    println(boxed::class.java.simpleName)

    // Convert between the two
    println(total(boxed.toIntArray()))
    val back: Array<Int> = primitive.toTypedArray()
    println(back.contentToString())

    // Only the boxed form can hold null
    val maybe: Array<Int?> = arrayOf(1, null, 3)
    println(maybe.contentToString())

    // Array<String> is Java's String[]
    val words: Array<String> = arrayOf("a", "b")
    println(words::class.java.simpleName)
}

Output

The JVM class names say it outright: int[], Integer[] and String[]. Because they are different types, passing boxed straight to total doesn't compile; here the error reads Argument type mismatch: actual type is 'Array<Int>', but 'IntArray' was expected. toIntArray() and toTypedArray() copy from one to the other. The same pairs exist for the other primitives: DoubleArray and Array<Double>, CharArray and Array<Char>, and so on.

3An array of a given size

Java's new int[5] is IntArray(5) in Kotlin: five elements at the type's default (0, false, 0.0). Add a lambda to compute each element from its index: IntArray(5) { i -> i * i }. The generic Array<T> always needs that lambda, because Kotlin has no default value for an arbitrary type. For an array of objects you will fill in later, arrayOfNulls<String>(3) gives an Array<String?> of nulls. fill() sets every element, or a range of them, to one value.

ArrayOfSize.kt
fun main() {
    // Primitive arrays start at the type's default
    val zeros = IntArray(5)
    val flags = BooleanArray(3)
    println(zeros.contentToString())
    println(flags.contentToString())

    // Pass a lambda to compute each element from its index
    val squares = IntArray(5) { i -> i * i }
    val labels = Array(3) { "item ${it + 1}" }
    println(squares.contentToString())
    println(labels.contentToString())

    // Same value everywhere
    val sevens = IntArray(4) { 7 }
    println(sevens.contentToString())

    // Objects with no value yet: an array of nulls
    val slots = arrayOfNulls<String>(3)
    slots[0] = "taken"
    println(slots.contentToString())

    // fill() overwrites in place
    zeros.fill(-1)
    println(zeros.contentToString())
    zeros.fill(9, fromIndex = 1, toIndex = 3)
    println(zeros.contentToString())
}

Output

IntArray(5) prints [0, 0, 0, 0, 0] and BooleanArray(3) prints [false, false, false]. In Array(3) { "item ${it + 1}" } the index arrives as it and the element type, String, comes from what the lambda returns. fill(9, fromIndex = 1, toIndex = 3) changes indexes 1 and 2 only (the end is exclusive), giving [-1, 9, 9, -1, -1]. Writing Array<Int>(3) without the lambda stops the compiler with No value passed for parameter 'init'.

4An empty array

emptyArray<String>() makes an empty Array<String>, and intArrayOf() or IntArray(0) an empty IntArray. With no values to look at, the compiler needs the element type from somewhere: the angle brackets or the declared type of the variable. A bare val a = arrayOf() fails with Cannot infer type for type parameter 'T'. Specify it explicitly. Keep in mind that an empty array stays empty: arrays have no add.

EmptyArray.kt
fun main() {
    // Typed empty arrays: the type has to come from somewhere
    val none = emptyArray<String>()
    val alsoNone: Array<String> = arrayOf()
    val noInts = IntArray(0)
    val noInts2 = intArrayOf()

    println(none.size)
    println(alsoNone.isEmpty())
    println(noInts.contentToString())
    println(noInts2.isNotEmpty())

    // Arrays can't grow: plus returns a new, longer array
    val more = none + "Ada" + "Grace"
    println(more.contentToString())
    println(none.size)

    // When you will add items one by one, a list fits better
    val list = mutableListOf<String>()
    list.add("Ada")
    list.add("Grace")
    println(list.toTypedArray().contentToString())
}

Output

All four declarations give empty arrays: size 0, and contentToString() prints []. none + "Ada" copies the array into a new one that is one element longer; none itself still has size 0. Doing that in a loop copies the whole array every time, so when the size grows, collect into a MutableList and call toTypedArray() at the end if an API needs an array. Calling none.add("Ada") doesn't compile: Unresolved reference 'add' on receiver of type 'Array<String>'.

52D arrays

Kotlin has no int[3][4] syntax. A 2D array is an array whose elements are arrays: Array(3) { IntArray(4) } builds three rows of four zeros, and grid[row][col] reads and writes a cell as in Java. Rows can be built from their indexes, listed with arrayOf and intArrayOf, or given different lengths for a jagged array. Print a nested array with contentDeepToString(), which goes into every level.

TwoDimensional.kt
fun main() {
    // A 3 x 4 grid of zeros: an array of IntArray rows
    val grid = Array(3) { IntArray(4) }
    grid[1][2] = 5
    println(grid.contentDeepToString())
    println("rows: ${grid.size}, columns: ${grid[0].size}")

    // Fill from the indexes
    val table = Array(3) { r -> IntArray(3) { c -> (r + 1) * (c + 1) } }
    for (row in table) println(row.joinToString(" "))

    // Known values, row by row
    val board = arrayOf(
        charArrayOf('X', 'O', 'X'),
        charArrayOf(' ', 'X', 'O'),
        charArrayOf('O', ' ', 'X'),
    )
    println(board[2][0])

    // Rows of different lengths (a jagged array)
    val jagged = arrayOf(intArrayOf(1), intArrayOf(2, 3), intArrayOf(4, 5, 6))
    println(jagged.contentDeepToString())

    // contentToString shows only the outer level
    println(jagged.contentToString().startsWith("[[I@"))

    // Trap: one shared row repeated three times
    val row = IntArray(2)
    val shared = Array(3) { row }
    shared[0][0] = 7
    println(shared.contentDeepToString())
}

Output

contentDeepToString() prints the grid as [[0, 0, 0, 0], [0, 0, 5, 0], [0, 0, 0, 0]]. On the same array, contentToString() prints each row as an address starting with [I@, Java's name for int[], which is why the startsWith check prints true. The last block is the trap: Array(3) { row } puts the same IntArray in all three slots, so one write shows up in every row as [[7, 0], [7, 0], [7, 0]]. Create the row inside the lambda, as in Array(3) { IntArray(2) }, to get three separate rows.

6Array vs List: which one to declare

Most Kotlin code uses List where Java code used arrays. An Array has a fixed size and elements you can always overwrite; a List from listOf is read-only, and a MutableList can also grow and shrink. Lists print their elements and compare by content with ==; arrays do neither, so you need contentToString() and contentEquals. Reach for an array when an API asks for one (a Java method, a vararg), or for large primitive data where IntArray avoids boxing. Lists get their own article: initialize a list.

ArrayVsList.kt
fun main() {
    // An Array is fixed-size but its elements can change
    val array = arrayOf(3, 1, 2)
    array[0] = 30
    // A List from listOf is read-only: no set, no add
    val list = listOf(3, 1, 2)

    // == on arrays compares identity, not content
    println(array == arrayOf(30, 1, 2))
    println(array contentEquals arrayOf(30, 1, 2))
    // Lists compare by content and print their elements
    println(list == listOf(3, 1, 2))
    println(list)

    // sort() sorts an array in place; sorted() returns a new list
    array.sort()
    println(array.contentToString())
    println(list.sorted())

    // Convert either way
    val fromArray: List<Int> = array.toList()
    val fromList: Array<Int> = list.toTypedArray()
    val ints: IntArray = list.toIntArray()
    println("$fromArray ${fromList.contentToString()} ${ints.sum()}")

    // An array goes into a vararg parameter with the spread operator *
    println(listOf(*array, 99))
}

Output

Two arrays with the same elements are not ==: the first line prints false, and contentEquals prints true. The two lists compare equal and print as [3, 1, 2] with no helper. array.sort() changes the array itself, while list.sorted() leaves list alone and returns a new one. toList(), toTypedArray() and toIntArray() copy between the two kinds. The * in listOf(*array, 99) spreads the array into the vararg, which is how you pass an array to any vararg function.

7Which should you use?

MethodGivesStarts withBest for
arrayOf(a, b, c)Array<T>The values you listKnown values of any object type, Java T[]
intArrayOf(1, 2, 3)IntArrayThe values you listKnown numbers, Java int[]
IntArray(n) { i -> … }IntArrayA value per indexValues from a formula
IntArray(n)IntArrayZerosA size now, values later, Java new int[n]
arrayOfNulls<T>(n)Array<T?>NullsObjects filled in later
emptyArray<T>()Array<T>NothingAn API that wants an array, with no items
Array(rows) { IntArray(cols) }Array<IntArray>ZerosGrids and matrices
mutableListOf<T>()MutableList<T>Nothing, growsAnything you add to or remove from

Frequently asked questions

What is the Kotlin equivalent of Java's String[]?

Array<String>. Create one with arrayOf("a", "b"), Array(n) { … } or emptyArray<String>(), and declare a parameter as args: Array<String>. For primitive arrays Kotlin has separate types: Java's int[] is IntArray, double[] is DoubleArray, boolean[] is BooleanArray, while Integer[] is Array<Int>.

What is the difference between IntArray and Array<Int>?

IntArray is a primitive int[] on the JVM; Array<Int> is an Integer[] of boxed objects. intArrayOf(1, 2) gives the first, arrayOf(1, 2) the second. They are not interchangeable: passing an Array<Int> where an IntArray is expected fails with Argument type mismatch: actual type is 'Array<Int>', but 'IntArray' was expected. Convert with toIntArray() and toTypedArray(). Prefer IntArray unless you need null elements.

Why does printing an array show something like [I@232204a1?

Arrays don't override toString(), so println(array) prints the JVM type name ([I for int[], [Ljava.lang.String; for String[]) and a hash code. Use array.contentToString() for [1, 2, 3], joinToString() for your own separator, and contentDeepToString() for arrays of arrays.

How do I create an array with only a size in Kotlin?

For primitives, IntArray(5), DoubleArray(5) or BooleanArray(5) start at 0, 0.0 or false. The generic Array<T> needs a lambda for the values, as in Array(5) { "" } or Array(5) { i -> i * 2 }; Array<Int>(5) alone fails with No value passed for parameter 'init'. For objects you fill in later, use arrayOfNulls<String>(5).

How do I add an element to an array in Kotlin?

You can't grow an array; its size is fixed. array + element returns a new array one element longer, which is fine once but copies the whole array each time. When you add items as you go, use a MutableList (mutableListOf<String>() then add) and call toTypedArray() at the end if you need an array.

How do I compare two arrays in Kotlin?

a == b on arrays checks whether they are the same object, so two arrays with equal elements compare as false. Use a contentEquals b to compare elements, and contentDeepEquals for arrays of arrays. Lists compare by content with plain ==.

How do I loop over an array with its index?

for (x in array) gives the elements, for (i in array.indices) gives the indexes, and for ((i, x) in array.withIndex()) gives both. array.forEachIndexed { i, x -> … } does the same as a lambda.

Run it yourself

Open any of these in the full Kotlin editor to tweak, run and share.

Kotlin playground