Javatpoint Logo
Javatpoint Logo

Kotlin Array

Array is a collection of similar data either of types Int, String etc. Array in Kotlin has mutable in nature with fixed size. Which means we can perform both read and writes operations on elements of array.

Syntax of array decleration:

It initializes the element of array of int type with size 5 with all elements as 0 (zero).

Kotlin array declaration - using arrayOf function

Kotlin array declaration - using arrayOf function

Let's see an example of array in Kotlin. In this example we will see how to initialize and traverse its elements.

Kotlin Array Example 1:

In this example, we are simply initialize an array of size 5 with default value as 0. The index value of array starts with 0. First element of array is placed at index 0 and last element at one less than the size of array.

Output:

0
0
0
0
0

Kotlin Array Example 2:

We can also able to rewrite the value of array using its index value. Since we can able to modify the value of array, so it is called as mutable in nature. For example:

Output:

0
10
0
15
0

Kotlin Array Example 3 - using arrayOf() and intArrayOf() function:

Array in Kotlin also declare using different functions such as arrayOf(), intArrayOf(), etc. Let's see the example arrayOf() and intArrayOf() function.

Output:

Ajay
Prakesh
Michel
John
Sumit

1
10
4
6
15

5
10
20
12
15

1
10
4
Ajay
Prakesh

5
10
15
20
25

Kotlin Array Example 4

Suppose that when we try to insert an element at index position greater than array size than what happen? It will throw an ArrayIndexOutOfBoundException. This is because the index value is not present where we want to insert the element. Due to this array is called fixed size length. Let's see the example:

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
	at ArrayListKt.main(Array.kt:4)

Kotlin Array Example 5 - traversing using range:

The Kotlin's array elements are also traverse using index range (minValue..maxValue) or (maxValue..minvalue). Let's see an example of array traversing using range.

Output:

5
10
20
12
15

5
10
20
12
15

Next TopicKotlin Collections




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA