Skip to main content

Kotlin Arrays

Kotlin array is collection of elements. That element are access by index. When we define an array then compiler are created its size. That size is set by programmer otherwise it will depends upone provide number of elements.

In Kotlin programming Array are defined by using of Array class. This class are providing lot of function to implement different type of Arrays.

How to define array in kotlin

There is following methods are available to declare array in kotlin programming.

Create arrays of primitive types in following ways.

fun main(args: Array<String>) {
    //Create primitive arrays
    var arrayData=IntArray(5) //create array of 5 integers element
    var shorData=ShortArray(7) //create array of 7 short integers element
    var longData=LongArray(4) //create array of 4 long element
    var byteData=ByteArray(3) //create array of 5 byte element
    var floatData=FloatArray(6) //create array of 5 float element
    var doubleData=DoubleArray(4)//create array of 5 double element
}

When we are initial value of primitive data type in this situation we can define the data type of array is like IntArray and assign the array element value by intArrayOf() function. For example.

fun main(args: Array<String>) {
    var intElement:IntArray=intArrayOf(1,2,3)
    var floatElement:FloatArray=floatArrayOf(1.6f,2.3f,3.2f)
    var bytesElement:ByteArray=byteArrayOf(12,2)
    var shortElement:ShortArray=shortArrayOf(100,200,300)
    var longElement:LongArray=longArrayOf(999999,33333333333,44444444)
    var doubleElement:DoubleArray=doubleArrayOf(1290.3,232.2)
   
    println(intElement.joinToString(separator=" "))
    println(floatElement.joinToString(separator=" "))
    println(bytesElement.joinToString(separator=" "))
    println(shortElement.joinToString(separator=" "))
    println(longElement.joinToString(separator=" "))
    println(doubleElement.joinToString(separator=" "))
}

Output

1 2 3
1.6 2.3 3.2
12 2
100 200 300
999999 33333333333 44444444
1290.3 232.2

Note that assigning element value is separate by comma. There is not always compulsory to mention the data type of variable in kotlin programming. Compiler are provide the data type by using of assigning value element.

//Create array of 5 integers element
var arrayData=IntArray(5)

In given of this statement, compiler are create an array of 5 integers. And their default value is 0.

fun main(args: Array<String>) {
  
  //Create array of 5 integers element
  var arrayData=IntArray(5)
  //display array elements 
  println(arrayData.joinToString(separator=" "))
}

Output

0 0 0 0 0

How to set custom default value to an array element ?. that is very simple in kotlin. See this example in this case set default value is to 10.

fun main(args: Array<String>) {
  
  //Create array of 5 integers element
  var arrayData=IntArray(5,{10}) //set default value
  //display array elements 
  println(arrayData.joinToString(separator=" "))
}

Output

10 10 10 10 10

Suppose in case we are need to create an array which can stored any kind data type values, In this situation we can use Array<Any> type. For example.

fun main(args: Array<String>){
    
    //Create an array of 5 element 
    val arrayData = Array<Any>(5){}
    
    //set array elements 
    arrayData[0]="Okay"
    arrayData[1]=123
    arrayData[2]=1344.2
    arrayData[3]=100000L
    arrayData[4]=123.33f 
    //display array elements 
    println(arrayData.joinToString(separator=" "))
}

Output

Okay 123 1344.2 100000 123.33

We can also create array by using of arrayOf() function. Here include few examples.

fun main(args: Array<String>) {
    var numberData:Array<Int> =arrayOf(1,2,3,4) //array of 4 integer
    var doubleData:Array<Double> = arrayOf(1.3,55.3,22.11)
    var strData:Array<String> = arrayOf("ABC","DEF","IJ")
    var longData:Array<Long> = arrayOf(20000,200000000,4444444,66666)
    println("\n Intger array data :")
    for(i in numberData){
        print(" "+i)
    }
    println("\n Double array data :")
    for(d in doubleData){
        print(" "+d)
    }
    println("\n String array data :")
    for(s in strData){
        print(" "+s)
    }
    println("\n Long array data :")
    for(l in longData){
        print(" "+l)
    }
}
Array Example in Kotlin

Output

 Intger array data :
 1 2 3 4
 Double array data :
 1.3 55.3 22.11
 String array data :
 ABC DEF IJ
 Long array data :
 20000 200000000 4444444 66666

In above all example are provide how to create array elements, We can also update mutable array elements by index value or use the method of array class.

fun main(args: Array<String>){
    var intElement:IntArray=intArrayOf(0,1,2,3,4,5)
    println("Before Updates ${intElement.joinToString(separator="   ")}")
    
    intElement[0]=100 //update value of index zero
   
    intElement.set(1,200) //update element by set method (index, value) 
    
    println("After Updates ${intElement.joinToString(separator="   ")}")
    
}}

Output

Before Updates 0   1   2   3   4   5
After Updates 100   200   2   3   4   5

In above example there are used two method to update array elements. Suppose we are need to create which are initial hold null values. In this situation we can use arrayOfNulls.

fun main(args: Array<String>){
    val numbers = arrayOfNulls<Int>(3) 
   
    println("Initial Value element  : ${numbers.joinToString(separator="  ")}")
    
    numbers[0]=90 //update values
    
    println("After modified element : ${numbers.joinToString(separator="  ")}")
    
    
}

Output

Initial Value element  : null  null  null
After modified element : 90  null  null

Array element are accessible by index value, In case we are access an array element which is not exist in array. In this situation compiler are produced an error. So best way first check the length of array then access array element or we can also use getOrNull(Int) method to retrieve array element. getOrNull(Int) are returning an element of array by given index. When index element is out of range then they are returns null value.

fun main(args: Array<String>){
 
    val intElement = intArrayOf(0,1,2) //make integer array
    // simple way 
    println(intElement[0])
    //using getOrNull(Int) method
    println(intElement.getOrNull(2)) //2 
    println(intElement.getOrNull(3)) //null
    
}
0
2
null

kotlin 2d Array

There is many ways to create 2d array in kotlin programming. Suppose that we are including element in row by row of 2d Array.

//display item of 2d array
fun printData(info:Array<IntArray>){
    
    for(item in info){
        for(position in item){
             print(" $position")
        }
        println()
    }
}
fun main(args: Array<String>) {

    val firstRow: IntArray = intArrayOf(1,2,3,4,5,6)
    val secondRow: IntArray = intArrayOf(7, 8, 9,10)
    //combine two rows
    val rowData: Array<IntArray> = arrayOf(firstRow, secondRow)
    printData(rowData)
}
2d kotlin array

Output

 1 2 3 4 5 6
 7 8 9 10

In this case both row of array element are different so that can be very effective. when create an array which array different number of columns. and array elements can be also use by its index value. for example

println(rowData[0][1]) //2
println(rowData[0][3]) //4
println(rowData[1][3]) //10

We can also define 2d array in single statements.

//display item of 2d array
fun printData(info:Array<IntArray>){
    
    for(item in info){
        for(position in item){
             print(" $position")
        }
        println()
    }
}
fun main(args: Array<String>) {

     //create static 2d array of integers
    val rowData: Array<IntArray> = arrayOf( 
        intArrayOf(11,12,13,14,15,16),
        intArrayOf(17, 18, 19),
        intArrayOf(20, 21, 22,23,24)
    )
    printData(rowData)
}

Output

 11 12 13 14 15 16
 17 18 19
 20 21 22 23 24

Most of case we are need to define the array of NXN. see this example.

fun printArray(info:Array<IntArray>){
    
    for(item in info){
        for(element in item){
             print(" $element")
        }
        println()
    }
}
fun main(args: Array<String>) {
    //create an array of 5X5
    var rows:Int =5
    var cols:Int =5
    val arrayData = Array(rows, {IntArray(cols)})
    printArray(arrayData)
}

Output

 0 0 0 0 0
 0 0 0 0 0
 0 0 0 0 0
 0 0 0 0 0
 0 0 0 0 0

Basic operation of kotlin Array

Get length of array

size is a member field of Array class that are provide the information of how many element are stored in array. that is automatically modified when add new element into the array and delete existing array element.

fun main(args: Array<String>) {
    var intInfo:IntArray=intArrayOf(1,2,3,4,5,6,7) 
    println(intInfo.size) //get size of array
}

Output

7

In case we are need to create a array which are add and remove element dynamically then we can choose mutable list.

fun main(args: Array<String>) {

//make mutableList
var myList: MutableList<String> = ArrayList()
   println("Before add element it's size : ${myList.size} ")
   myList.add("1") //add first element
   myList.add("2") //add second element
   myList.add("3") //add third element
   println("Elements: ${myList}")
   println("After add element it's size : ${myList.size} ")
}

Output

Before add element it's size : 0 
Elements: [1, 2, 3]
After add element it's size : 3 

Get array element

Here give few examples how to get array elements.


fun main(args: Array<String>) {

   var arrayElement:IntArray=intArrayOf(10,20,30,40,50)
   println(arrayElement.first()) //print element first element
   println(arrayElement.last()) //print element of last element
   println(arrayElement.get(2)) //print second index element 
   println(arrayElement[3]) //print third index element
}

Output

10
50
30
40

Here first() function are returning the value of index zero. and last() function are returning the value of (N-1) value, Here N is number of elements. And we can also use get() method this are accept one integer index value. And other methods are similar to get element by index.

Slice Array element

Slice means small portion of elements, That is very useful when we are need to create new array with the help of existing array. We can gets the specifying grouping element of array in between range by this function.

fun main(args: Array<String>) {

   var arrayElement:IntArray=intArrayOf(1,2,3,4,5,6,7,8,9)
   println(arrayElement.sliceArray(4..8).joinToString(separator=" ")) //print element
 
}

Output

5 6 7 8 9

iterating array element

We can iterate array elements in a two ways first use For-loop that is generally use. See this example.

fun main(args: Array<String>) {
    var intInfo:IntArray=intArrayOf(1,2,3,4,5,6,7) 
    for(element in intInfo){
        println(element)
    }
}

Output

1
2
3
4
5
6
7

We are also use while-loop.

fun main(args: Array<String>) {
    val arrayInfo:IntArray=intArrayOf(1,2,3,4,5,6,7) 
    var index=0;     
    while(index<arrayInfo.size){
        println("index: $index  value: ${arrayInfo.get(index)} ")
        index++
    }
}

Output

index: 0  value: 1 
index: 1  value: 2 
index: 2  value: 3 
index: 3  value: 4 
index: 4  value: 5 
index: 5  value: 6 
index: 6  value: 7 

Create an array elements between range of two value and specified intervals.

fun main(args: Array<String>) {
    var arrayInfo:IntArray =IntRange(1, 20).step(2).toList().toIntArray()
    for(i in arrayInfo){
        println(i)
    }
 
}

Output

1
3
5
7
9
11
13
15
17
19

Another way

fun main(args: Array<String>) {
    var arrayInfo:IntArray =IntArray(10,{i->(i*2)})
    for(i in arrayInfo){
        println(i)
    }
 
}

Output

0
2
4
6
8
10
12
14
16
18

Another way

fun main(args: Array<String>){
    var numbers = Array<Int>(size = 5, init = { index -> index*2 })

    print(numbers.joinToString(separator=" ")) 
}

Output

0 2 4 6 8

Modified array element

We can modify array elements in following ways.

fun main(args: Array<String>) {
    var arrayInfo:IntArray =intArrayOf(1,2,3,4,5)
    println("Before modified array :")
    for(i in arrayInfo){
        println(i)
    }
    arrayInfo[0]=10 //using of index
    arrayInfo.set(4,50) //using of set method
    println("After modified array :")
    for(i in arrayInfo){
        println(i)
    }
 
}

Output

Before modified array :
1
2
3
4
5
After modified array :
10
2
3
4
50

Sort Array element

fun main(args: Array<String>) {
    val arrayInfo:IntArray=intArrayOf(6,8,1,5,9,4,7,5) 
    arrayInfo.sort()
    for (i in arrayInfo){
        print(" $i")
    }
}

Output

 1 4 5 5 6 7 8 9

We can also sort element within specified index range.

fun main(args: Array<String>) {
    val arrayInfo:IntArray=intArrayOf(6,8,1,5,9,4,7,5)
    //sort element within specified index range
    //index 0 to 4
    arrayInfo.sort(fromIndex=0,toIndex=4)
    for (i in arrayInfo){
        print(" $i")
    }
}

Output

 1 5 6 8 9 4 7 5

Passing array to function argument

fun displayElement(arrayData:IntArray){
    //Display array element
    for (i in arrayData){
        print(" $i");
    }
}
fun main(args: Array<String>) {
    //create an array element
    val arrayInfo:IntArray=intArrayOf(6,8,1,5,9,4,7,5) 
    //send array to function
    displayElement(arrayInfo)  
}
Pass an array to method in kotlin
 6 8 1 5 9 4 7 5

When we modify element value of passing array. then that are reflected and update original arrays. For example.

fun changeElement(arrayData:IntArray){
    if(arrayData.size>0){
         //Modified first and last element in given integer array
         arrayData[0]=100
         arrayData[arrayData.size-1]=200
    }
   
}

fun displayElement(arrayData:IntArray){
    
    //Display array element
    for (i in arrayData){
        print(" $i");
    }
}
fun main(args: Array<String>) {
    //create an array element
    val arrayInfo:IntArray=intArrayOf(6,8,1,5,9,4,7,5)
    
    println("Before Change")
    displayElement(arrayInfo)
    
    println("\nAfter Change")
    changeElement(arrayInfo)
    displayElement(arrayInfo)
}

Output


Before Change
 6 8 1 5 9 4 7 5
After Change
 100 8 1 5 9 4 7 200

Copy Array element

When we are assign one array variable to another similar type of array they are internally assign the reference of other array. In case we are needed to copy array element then we can used copyof() function.

fun main(args: Array<String>) {
    //create an array element
    var firstArray:IntArray=intArrayOf(1,2,3,4,5,6,7)
    var secondArray:IntArray=firstArray.copyOf()
    //update element of first array   
    firstArray[0]=10
    firstArray[1]=20
    firstArray[2]=30
    println(firstArray.joinToString(separator=" "))
    println(secondArray.joinToString(separator=" "))
}
Copy Array In Kotlin Programming
10 20 30 4 5 6 7
1 2 3 4 5 6 7

Note that modified the value of first array element value to second array. And after that modified the element value of first array.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment