We can use the arrayOf()
function to create a new array and pass the array elements as arguments to the function. Syntax :
arrayOf(/* Elements */)
Example :
fun main() {
val nums = arrayOf(12, 15, 20, 35) // Creates an array of 4 ints
}
We can create a new int
array using IntArray
constructor too. We have to pass a size in it and it’ll return an array of that size full of zeroes :
IntArray(/* Elements */)
Example :
fun main() {
val nums = IntArray(3) // Creates an array of 3 ints (zeroes)
}
Similarly, we can create FloatArray
, DoubleArray
, LongArray
, BooleanArray
& CharArray. Numerical arrays are filled with zeroes, BooleanArray
with false
and CharArray
with character of code 0.