KOTLIN Tutorial



ARRAYS IN KOTLIN


Arrays in Kotlin

Arrays in Kotlin are used to store multiple values of the same type in a single variable. Kotlin arrays are easy to work with and come with built-in functions.


1. Declaring an Array

You can declare an array using arrayOf() or using Array() constructor.

// Using arrayOf()
val numbers = arrayOf(1, 2, 3, 4, 5)

// Using Array() constructor
val squares = Array(5) { i -> (i * i) }

println(numbers.joinToString(", "))   // Output: 1, 2, 3, 4, 5
println(squares.joinToString(", "))   // Output: 0, 1, 4, 9, 16
  

2. Accessing Elements

Array elements can be accessed using an index, starting from 0.

val colors = arrayOf("Red", "Green", "Blue")
println(colors[0])   // Output: Red
println(colors[1])   // Output: Green
println(colors[2])   // Output: Blue
  

3. Modifying Elements

You can modify array elements by using their index.

val fruits = arrayOf("Apple", "Banana", "Cherry")
fruits[1] = "Blueberry"

println(fruits.joinToString(", "))  // Output: Apple, Blueberry, Cherry
  

4. Array Size and Checking

You can get the size of an array using the size property.

val numbers = arrayOf(10, 20, 30, 40)
println("Array size: ${numbers.size}")  // Output: Array size: 4
  

5. Iterating Through Arrays

You can loop through an array using a for loop:

val names = arrayOf("Alice", "Bob", "Charlie")
for (name in names) {
    println(name)
}
  
๐Ÿ’ก Tip: Use joinToString() to quickly format arrays into a readable string.

6. Array Functions

Kotlin arrays come with several built-in functions to make them even more powerful:

val numbers = arrayOf(1, 2, 3, 4, 5)
println(numbers.sum())     // Output: 15
println(numbers.average()) // Output: 3.0
println(numbers.maxOrNull())  // Output: 5
println(numbers.sortedArray().joinToString(", ")) // Output: 1, 2, 3, 4, 5
  
๐Ÿ” Use maxOrNull() to safely get the maximum value in an array.

7. Array of Nulls

You can also create an array that contains null values:

val nullArray = arrayOfNulls(5)
println(nullArray.joinToString(", "))  // Output: null, null, null, null, null
  

๐Ÿงช Try It Yourself

Practice these challenges:

  • Create an array of your favorite movies.
  • Modify the array to change one movie.
  • Sort the array in alphabetical order.

๐ŸŒŸ Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review