Start learning free

LESSON 89 OF 348 · ARRAYS I

Static Arrays in Kotlin: IntArray, arrayOf and arrayOfNulls

Lesson Read the full explanation

When we're dealing with large amounts of data, we want to make sure we can organize and manage it properly.

In Kotlin, we use arrays to store several pieces of data in one place. The items in an array must be of the same data type.

A static array or fixed array is an array for which the size / length is determined when the array is created and/or allocated.


Creation:

We create a static array by calling a builder with its length, for example arrayOfNulls<String> for strings or IntArray for integers:

val arrayOfStrings = arrayOfNulls<String>(3)

In this program we created an array named arrayOfStrings that consists of 3 String items.

These 3 items are null (no value given yet) initially.


Creation & Initialization:

There is a way to initialize an array at creation by using the arrayOf(...) builder, listing the values inside the parentheses and putting a comma between each entry, like this:

val arrayOfStrings = arrayOf("AlgoCademy", "coding", "static arrays")

We created an array named arrayOfStrings which consits of 3 String items: "AlgoCademy", "coding" and "static arrays".


Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    KOTLIN · ARRAYS I

    Static Arrays in Kotlin, explained

    What a static array is

    An array stores several values of the same type under one name. A static (or fixed) array has its size decided when it is created, and that size never changes. If you need to add or remove items later, you want a list instead, which a later lesson covers.

    Kotlin has no special array syntax. Arrays are objects, and you create them by calling a function. Which function you call depends on whether you have the values yet.

    Creating an array of a given size

    When you know how many items you need but not their values, ask for an array of that size:

    val zeros = IntArray(5)
    val names = arrayOfNulls<String>(3)
    println(zeros.contentToString())
    println(names.contentToString())
    
    [0, 0, 0, 0, 0]
    [null, null, null]
    

    IntArray(5) makes five integers, all starting at 0. The other primitive arrays work the same way: DoubleArray starts with 0.0, BooleanArray with false.

    arrayOfNulls<String>(3) makes room for three strings, but there are no strings yet. Every slot holds null, so the type of the array is Array<String?>: the ? says each element may be missing. You have to fill the slots before you can use them as ordinary strings.

    Creating an array with values

    When you already know the values, list them in arrayOf, or in intArrayOf for integers:

    val fruits = arrayOf("mango", "kiwi", "grapefruit")
    val ages = intArrayOf(14, 32, 50, 21)
    

    The array's size is the number of values you list: 3 for fruits, 4 for ages. Kotlin infers the element type from the values, so fruits is an Array<String>.

    Common mistakes and gotchas

    • Array<Int> and IntArray are different types. IntArray stores plain int values and is the usual choice for numbers. Array<Int>, which arrayOf(1, 2, 3) creates, stores boxed objects. A function that takes an IntArray won't accept an Array<Int>.
    • Printing an array doesn't show its contents. println(fruits) prints a type name and a hash code, something like [Ljava.lang.String;@1b6d3586. Use contentToString() to see the elements.
    • val doesn't freeze the array. It stops the variable from being pointed at a different array, but the items can still be changed.
    • The size can't grow. An array made with IntArray(20) has 20 slots for good. There is no add on an array.
    • Nullable slots need care. Reading names[0].length on an arrayOfNulls<String> array doesn't compile: the compiler reports that only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver.

    The exercise

    1. Create numbers. The task asks for integers and a fixed size of 20, which is exactly what IntArray(20) gives: 20 elements, all 0.
    2. Create fruits. The values are known, so use arrayOf and list the three strings in the order given.
    val numbers = IntArray(20)
    val fruits = arrayOf("mango", "kiwi", "grapefruit")
    

    Nothing prints here: the exercise only creates the arrays. To see them, add println(numbers.size), which prints 20, and println(fruits.contentToString()), which prints [mango, kiwi, grapefruit].

    More ways to build and use arrays

    The other primitive array types follow the pattern of IntArray: DoubleArray(2) holds [0.0, 0.0] and BooleanArray(2) holds [false, false]. Each has a matching builder with values, such as doubleArrayOf(1.5, 2.5).

    If every slot should start with a computed value rather than a default, give the constructor a lambda. The lambda receives the index of each slot and returns its value:

    val evens = Array(3) { it * 2 }
    println(evens.contentToString())
    
    [0, 2, 4]
    

    Two variables, one array

    An array is an object, so assigning it to another variable copies the reference, not the elements. After val b = a, both names refer to the same array, and a change through b shows up through a. To get an independent array, call copyOf():

    val a = intArrayOf(1, 2, 3)
    val b = a
    b[0] = 99
    val c = a.copyOf()
    c[0] = 5
    println(a.contentToString())
    println(c.contentToString())
    
    [99, 2, 3]
    [5, 2, 3]
    

    Choosing between an array and a list

    Pick an array when the number of items is known and stays the same, such as the twelve months of a year, the pixels of a fixed-size image or the results of a fixed number of tests. Pick a list when items come and go. Arrays also give you the primitive types IntArray, DoubleArray and so on, which store plain numbers without wrapping each one in an object.

    A good habit is to create the array with the right size from the start. If you find yourself wanting to add one more item, that is the sign to switch to a list.

    Key takeaways

    • An array holds items of one type, and its size is fixed when it is created.
    • IntArray(n) creates n zeros; arrayOfNulls<T>(n) creates n empty slots.
    • arrayOf(...) and intArrayOf(...) create an array from listed values.
    • Use contentToString() to print the elements.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free