English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of Kotlin Examples
In this program, you will learn different methods to print given array elements in Kotlin.
fun main(args: Array<String>) { val array = intArrayOf(1, 2, 3, 4, 5) for (element in array) { println(element) } }
When the program is run, the output is:
1 2 3 4 5
In the above program, for-Each loop is used to iterate over the given array array.
It accesses each element in the array and uses println() to print it.
import java.util.Arrays fun main(args: Array<String>) { val array = intArrayOf(1, 2, 3, 4, 5) println(Arrays.toString(array)) }
When the program is run, the output is:
[1, 2, 3, 4, 5]
In the above program, the for loop is replaced with a single line of code using the Arrays.toString() function.
As you can see, this provides clean output without any additional code lines.
import java.util.Arrays fun main(args: Array<String>) { val array = arrayOf(intArrayOf(1, 2), intArrayOf(3, 4), intArrayOf(5, 6, 7))}} println(Arrays.deepToString(array)) }
When the program is run, the output is:
[[1, 2], [3, 4], [5, 6, 7]]
In the above program, since each element of the array contains another array, only Arrays.toString() will print the address of the elements (nested arrays).
To get numbers from the internal array, we only need to use another function Arrays.deepToString(). This gives us the number1,2, and so on, we are looking for.
This function also applies to3多维数组。
The following is the equivalent Java code:Java Program to Print Array