Start learning free

LESSON 95 OF 414 · ARRAYS I

Accessing Static Array Elements in Scala

Lesson Read the full explanation

Arrays are ordered, meaning each element has a numbered position known as its index. We access an array element by referring to its index number.

Arrays use zero-based indexing, so the first element in an array has an index of 0, the second element has an index of 1, etc.

We use the index in parentheses (()) after the name of the array to access the element:

val animals = Array("cat", "dog", "parrot")

println(animals(0)) // Output: cat
println(animals(1)) // Output: dog
println(animals(2)) // Output: parrot

Assignment
Follow the Coding Tutorial and let's practice with accessing elements!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    SCALA · ARRAYS I

    Accessing Static Array Elements in Scala, explained

    Indexing with parentheses

    Each element of an array has a numbered position called its index. Indexes start at 0, so the first element is at index 0, the second at index 1, and so on. To read an element, write the index in parentheses after the array's name:

    val animals = Array("cat", "dog", "parrot")
    println(animals(0)) // cat
    println(animals(1)) // dog
    println(animals(2)) // parrot
    

    Scala uses parentheses here, not square brackets. Square brackets hold type parameters (Array[String]). Writing animals[0] doesn't compile: the error says that method apply in class Array does not take type parameters. The reason is that animals(0) is a call to the array's apply method.

    The value you get back has the array's element type. An element of an Array[Int] is a plain Int, so you can use it in arithmetic right away.

    The exercise

    The lesson starts with two arrays:

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

    Step 1: the second fruit

    Counting from zero, the second item is at index 1, not 2. println(fruits(1)) prints kiwi.

    Step 2: the sum of the first three ages

    The first three items are at indexes 0, 1 and 2. Add them inside the call: println(ages(0) + ages(1) + ages(2)). The expression is computed first, and println receives the result, 96 (14 + 32 + 50).

    Step 3: last minus first

    The array has four elements, so its last index is 3. println(ages(3) - ages(0)) prints 7 (21 - 14).

    The finished program

    val fruits = Array("mango", "kiwi", "grapefruit")
    val ages = Array(14, 32, 50, 21)
    println(fruits(1))
    println(ages(0) + ages(1) + ages(2))
    println(ages(3) - ages(0))
    

    It prints:

    kiwi
    96
    7
    

    Looping over the indexes

    When you need every element, you can count the indexes yourself. The range 0 until ages.length runs from 0 up to, but not including, the length:

    for (i <- 0 until ages.length) {
        print(ages(i) + " ")
    }
    

    This prints 14 32 50 21 . Because until excludes its upper end, the last index used is 3, the last valid one. Scala also provides ages.head for the first element and ages.last for the last, which give 14 and 21 here without any index arithmetic.

    Gotchas

    • Off by one. The element at index n is the (n + 1)th item. An array with four elements has indexes 0 to 3, so the last index is one less than the length.
    • Out of range. Reading an index outside the array throws an ArrayIndexOutOfBoundsException at run time. The compiler does not check indexes.
    • Brackets. ages[3] is a compile error, not a different way to write ages(3).
    • Adding strings. + on integers adds them, but on strings it joins them. fruits(0) + fruits(1) is "mangokiwi".

    Why the sum works without conversion

    In ages(0) + ages(1) + ages(2), each part is an Int, and Scala evaluates the additions from left to right. Inside the parentheses of println, the whole sum is finished before printing starts. If you want to keep the result, store it in a val, for example val total = ages(0) + ages(1) + ages(2), and print total afterwards.

    Reading the last element

    You don't have to know the length in advance to reach the end. The index of the last element is ages.length - 1, so ages(ages.length - 1) is 21 and ages(ages.length - 2) is 50. This form keeps working if you later edit the code to create an array of another length, while a hard-coded ages(3) would not.

    Key takeaways

    • Read an element with array(index).
    • Indexes run from 0 to length - 1.
    • Elements keep their own type, so numbers from an Array[Int] can be added directly.
    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free