Printing an array in Kotlin involves displaying all elements of the array, either sequentially or with specific formatting. This article explores Kotlin Program to Print an Array in three different ways, providing real examples with varying solutions and outputs.
1. Using joinToString
Function
1.1 Example 1: Printing Int Array
Kotlin
fun main() {
val array = intArrayOf(1, 2, 3, 4, 5)
println("Array Elements: ${array.joinToString()}")
}
Output:
Kotlin
Array Elements: 1, 2, 3, 4, 5
1.2 Example 2: Printing String Array
Kotlin
fun main() {
val array = arrayOf("Kotlin", "Java", "Python")
println("Array Elements: ${array.joinToString()}")
}
Output:
Kotlin
Array Elements: Kotlin, Java, Python
2. Using a Loop to Print Elements
2.1 Example 3: Printing Char Array
Kotlin
fun main() {
val array = charArrayOf('a', 'b', 'c', 'd', 'e')
println("Array Elements:")
for (element in array) {
println(element)
}
}
Output:
Kotlin
Array Elements:
a
b
c
d
e
Explanation and Summary
- Example 1: The
joinToString
function is used to create a string representation of the array elements with default settings. - Example 2: Similarly, arrays of reference types like
Array<String>
can be printed usingjoinToString
. - Example 3: For more control over formatting or when dealing with arrays of primitive types like
CharArray
, a loop can be used to iterate through elements and print them individually.
The examples showcase different approaches to print arrays in Kotlin, highlighting the flexibility to customize output format and handle various array types efficiently. Whether using joinToString
for concise printing or a loop for more specific formatting needs, Kotlin provides intuitive methods to display array elements effectively.