So far we have seen how to create an empty array so that we can initialise it later.
Now, let us see, how can we initialise an Array while creation.
fun main() { var arr = arrayOf(6, 9, 12, 2, 7) for (i in 0..4) { println(arr[i]) } }
So, in the above code, we have declared an Array 'arr' that is going to store the numbers 6, 9, 12, 2 and 7.
So, the first line declares an array, 'arr' and assigns values to it.
Now, internally what happens is, 5 empty locations are created with indexes from '0' to '4' and the numbers 6, 9, 12, 2 and 7 are assigned to it..
And the locations looks like the below image.
Now that we have all the 5 numbers stored in the Array. We can use another 'for loop' to display all the numbers.
for (i in 0..4) { println(arr[i]) }
The above 'for loop' picks all the numbers one by one and displays on the screen.
Although we have inserted numbers in the Array 'arr'. But with 'toArray()' function it is also possible that you can initialise the array with Strings and floating point numbers.
Let us see in the below example.
fun main() { var arr = arrayOf("John" , 9, 2.57) for (i in 0..2) { println(arr[i]) } }
So, we have created an array 'arr' and initialised it with John, 9 and 2.57.
And they are printed successfully.
But what if, we want an Array to store only numbers or Strings.
Luckily, Kotlin provides a way to do it.
Let us see them below.
fun main() { var arr = arrayOf<Int>("John" , 9, 2.57) for (i in 0..2) { println(arr[i]) } }
So, we have created an array 'arr' that would store numbers only.
But initialised the array with John, 9 and 2.57.
And as we can see the output. It ended up with an error.
So, as we can see the above array would accept integers only.
fun main() { var arr = arrayOf<Int>(6, 9, 12, 2, 7) for (i in 0..4) { println(arr[i]) } }
Similarly, to make an array hold only strings, we can define it in the same way.
Declaring an Array that is going to hold 5 String/names
fun main() { var arr = arrayOf<String>("Mohan", "John", "Paul", "Kriti", "Salim") for (i in 0..4) { println(arr[i]) } }
Similarly, for data types like float, double e.t.c. We can follow the same process.
In the next tutorial, we will see, how to iterate the elements of the Array in a different way.