Array is data structure consisting of collection of elements. Each item in the array can be identified or called by a key or position which is starting from zero. So that we can call the elements using the key.
Arrays can be integer array and string array, here we are trying learn the difference of array in Kotlin and java. How can we use array in Kotlin and Java. We are using same example in both language.
Array in Java
Below sample code for an integer array in java. It is printing with for loop in Java.
public class MyJavaClass {
public static void main(String[] args){
int [] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int number=0; number<10; number ++){
System.out.println(numbers[number]);
}
}
}
Array In Kotlin
Below sample code of an integer array in Kotlin with data from 1 to 10. It will be printed using a for loop as we done in above, java sample code.
fun main(){
val numbers : Array = arrayOf(1,2,3,4,5,6,7,8,9,10)
for (number : Int in numbers){
println(numbers[number-1])
}
}
Run the code as below.
Thank You.