Kotlin Program to Concatenate Two Arrays

In Kotlin, concatenating two arrays involves combining the elements of both arrays to create a new array containing all the elements from both arrays. This article explores Kotlin Program to Concatenate Two Arrays providing three real examples with different solutions and outputs.

1. Basic Concatenation Using plus Operator

1.1 Example 1: Concatenating Int Arrays

Kotlin
fun main() {
    val array1 = intArrayOf(1, 2, 3)
    val array2 = intArrayOf(4, 5, 6)
    
    val resultArray = array1 + array2
    
    println("Concatenated Array: ${resultArray.joinToString()}")
}

Output:

Kotlin
Concatenated Array: 1, 2, 3, 4, 5, 6

1.2 Example 2: Concatenating String Arrays

Kotlin
fun main() {
    val array1 = arrayOf("Hello", "World")
    val array2 = arrayOf("Kotlin", "Programming")
    
    val resultArray = array1 + array2
    
    println("Concatenated Array: ${resultArray.joinToString()}")
}

Output:

Kotlin
Concatenated Array: Hello, World, Kotlin, Programming

2. Concatenation Using concat Function

2.1 Example 3: Concatenating Char Arrays

Kotlin
fun main() {
    val array1 = charArrayOf('a', 'b', 'c')
    val array2 = charArrayOf('d', 'e', 'f')
    
    val resultArray = array1.concat(array2)
    
    println("Concatenated Array: ${resultArray.joinToString()}")
}

Output:

Kotlin
Concatenated Array: a, b, c, d, e, f

Explanation and Summary

  • Example 1: Using the plus operator (+) directly concatenates arrays of primitive types like IntArray.
  • Example 2: Similarly, arrays of reference types like Array<String> can be concatenated using +.
  • Example 3: For arrays of other types, such as CharArray, the concat function provides a concise way to concatenate arrays.