Array access
- Kotlin course
- Beginner
- Lesson 54/116
- 4 min
Learn to access array elements by index.
Array access
Array elements are accessed by index: array[0] gives the first element. Indices start at 0.
val fruits = arrayOf("apple", "pear", "cherry")
println(fruits[0]) // apple
println(fruits[2]) // cherryfruits[0] is the first element ("apple"), fruits[2] the third ("cherry"). Since indices start at 0, the last index of an N-element array is N-1.
Going beyond the bounds throws IndexOutOfBoundsException.
Index bounds and mutation
Array elements can be both read and written with arr[index] (if declared with var).
val nums = intArrayOf(3, 7, 2)
println(nums[1]) // 7
nums[1] = 9
println(nums[1]) // 9Here nums[1] first gave 7; then nums[1] = 9 changed it to 9. Even with val nums, elements can be changed; only the array itself cannot be reassigned.
Index starts at 0 and goes up to size - 1.
Practice Print the first and last element
Write a fun main(). Create an array with val fruits = arrayOf("apple", "pear", "cherry"). Print the first element with println(fruits[0]) and the last with println(fruits[2]).
Starter code
fun main() {
// Print the first and last element
}Sample solution
fun main() {
val fruits = arrayOf("apple", "pear", "cherry")
println(fruits[0])
println(fruits[2])
}Expected output
apple cherry
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the indices
| Term | Meaning |
|---|---|
arr[0] |
First element |
arr[1] |
Second element |
arr[N-1] |
Last element |
arr[N] |
Error (out of bounds) |
2 val arr = arrayOf("a", "b", "c") — what does arr[0] return?
- "a" Correct answer
- Error
- "b"
- "c"
Explanation: arr[0] gives "a", the first element.
3 Complete the first element access
println(fruits[____])
println(fruits[0])
Explanation: fruits[0] gives the first element.