Array size
- Kotlin course
- Beginner
- Lesson 55/116
- 5 min
Learn array info with size and indices.
Array size
The size of an array is given by the size property. indices gives the range of valid indices (0..size-1), lastIndex gives the last index.
val nums = intArrayOf(3, 7, 2, 5)
println(nums.size) // 4
println(nums.lastIndex) // 3
println(nums.indices) // 0..3In a 4-element array, size is 4, lastIndex is 3 (since indices start at 0), indices is 0..3. These are useful in loops and bounds checks.
size is a property; no parentheses needed.
Practice Print size and last index
Write a fun main(). Create an array with val nums = intArrayOf(3, 7, 2, 5). Print the size with println(nums.size) and the last index with println(nums.lastIndex).
Starter code
fun main() {
// Print size and last index
}Sample solution
fun main() {
val nums = intArrayOf(3, 7, 2, 5)
println(nums.size)
println(nums.lastIndex)
}Expected output
4 3
Iterating with indices
indices returns a range; it is useful for iterating by index in a for loop.
val nums = intArrayOf(3, 7, 2, 5)
for (i in nums.indices) {
println(nums[i])
}This takes each index in turn and accesses the element with nums[i]. indices is the range from 0 to lastIndex.
Index-based iteration is useful when you also need the element's position.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the size call
println(nums.____)
println(nums.size)
Explanation: nums.size gives the element count.
2 Match the size properties
| Term | Meaning |
|---|---|
size |
Element count |
lastIndex |
Last index |
indices |
Index range |
0..3 |
4-element array range |
3 In a 4-element array, what is lastIndex?
- 4
- 3 Correct answer
- 0
- 1
Explanation: Since indices start at 0, the last index is 3.