Print an Array using Kotlin

thumbnail

In this tutorial, you will learn about different techniques to print elements from a given array using Kotlin. There will be 3 example that will show to you, such as: Print an Array using standard library Arrays, Print an Array using For-loop, and Print a Multi-dimensional array.

Example 1: Print an Array using Standard Library

In the first example, the output will be printed by single line of code using Arrays.toString() function. This is the easiest way to print an array.

import java.util.Arrays

fun main(args: Array<String>) {
    val array = intArrayOf(1, 3, 5, 7, 9)
    println(Arrays.toString(array))
}

The output will be:

[1, 3, 5, 7, 9]

Example 2: Print an Array using For-loop

The second example will be about printing array value using for-loop. The for-each loop is used to iterate over the given array.  It accesses each element in the array and print using println().

fun main(args: Array<String>) {
    val array = intArrayOf(0, 2, 4, 6, 8)
    for (element in array) {
        println(element)
    }
}
0
2
4
6
8

Example 3: Print a Multi-dimensional Array

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))
}

The output will be:

[[1, 2], [3, 4], [5, 6, 7]]

Since each element in array contains another array, we can use Arrays.toString() to print the address of the elements (nested array). To get the number from the inner array, we can also use Arrays.deepToString() function. This gets us the number 1,2 and so on. The function also works for 3-dimensional arrays.

You can find another tutorial about kotlin here.

Back To Top