How to create an array in Kotlin like in Java by just providing a size?


Kotlin is a cross platform statistically typed language based upon JVM. Kotlin is designed in such a way that it is interoperate fully with Java and JVM. In Java, we can simply create an array by providing a size.

Example – Array of Specific Size in Java

The following example demonstrates how to create an array of a specific size in Java.

public class MyClass {
   public static void main(String args[]) {
      int a[]=new int[5];
      for(int i=0;i<=5;i++){
         System.out.println(a[i]);
      }
   }
}

Output

As we have created an empty array, it will have the default values of 0’s in it.

0
0
0
0
0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 
   at MyClass.main(MyClass.java:5)


Example – Array of Specific Size in Kotlin

In this example, we will see how we can create an array of specific size in Kotlin.

fun main(args: Array<String>) {
   // declaring null array of size 5
   // equivalent in Java: new Integer[size]
   val arr = arrayOfNulls<Int>(5)
   print("Array of size 5 containing only null values: 
")    println(arr.contentToString())        val strings = Array(5) { "n = $it" }    print("
Array of size 5 containing predefined values:
")    println(strings.contentToString())     val arrZeros = Array(5) { 0 }    print("
Array of size 5 containing predefined values:
")    println(arrZeros.contentToString()) }

Output

It will generate the following output −

Array of size 5 containing only null values:
[null, null, null, null, null]

Array of size 5 containing predefined values:
[n = 0, n = 1, n = 2, n = 3, n = 4]

Array of size 5 containing predefined values:
[0, 0, 0, 0, 0]

Updated on: 16-Mar-2022

778 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements