Labs ICT
โญ Pro Login

Arrays

Arrays let you store multiple values of the same type in one container. Think of them as a numbered list where each item has an index starting at 0.

Creating arrays with arrayOf

The simplest way to make an array is arrayOf().


fun main() {
  val numbers = arrayOf(1, 2, 3, 4, 5)
  val names = arrayOf("Alice", "Bob", "Charlie")
  println(numbers[0])
  println(names[1])
}
    

Kotlin infers the type from the values you pass.

Try it Yourself โ†’

Typed arrays: IntArray, BooleanArray, etc.

For primitives, Kotlin has specialized arrays that avoid boxing overhead.


fun main() {
  val scores = intArrayOf(90, 85, 88, 92)
  val flags = booleanArrayOf(true, false, true)
  println(scores[2])
}
    

You also have doubleArrayOf(), charArrayOf(), and more.

Try it Yourself โ†’

Array indexing and size

Access items by their index with []. The size property tells you how many elements are in the array.


fun main() {
  val colors = arrayOf("Red", "Green", "Blue")
  println("First: ${colors[0]}")
  println("Last: ${colors[colors.size - 1]}")
  println("Total: ${colors.size}")
}
    

Remember: indices start at 0, so the last index is always size - 1.

Try it Yourself โ†’

Modifying array elements

Arrays are mutable โ€” you can change elements by assigning to an index.


fun main() {
  val numbers = intArrayOf(1, 2, 3)
  numbers[1] = 99
  println(numbers.joinToString())
}
    

joinToString() converts the array to a readable string.

Try it Yourself โ†’

Iterating over an array

Use a for loop to walk through every element.


fun main() {
  val fruits = arrayOf("Apple", "Banana", "Cherry")
  for (fruit in fruits) {
    println(fruit)
  }
}
    

Need the index too? Use indices.


fun main() {
  val fruits = arrayOf("Apple", "Banana", "Cherry")
  for (i in fruits.indices) {
    println("$i: ${fruits[i]}")
  }
}
    
Try it Yourself โ†’

๐Ÿงช Quick Quiz

Which function creates an array in Kotlin?