EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Kotlin

Array & String

In Kotlin, arrays are used to store multiple elements of the same type in a single variable. Arrays are a fundamental data structure that allows efficient storage and retrieval of data. Kotlin provides various methods and functions to operate on arrays, making them versatile and powerful.

Creating Arrays:

1. Using arrayOf(): This method creates an array of specified elements.

Syntax:

val intArray = arrayOf(1, 2, 3, 4)
val stringArray = arrayOf("one", "two", "three")

Example

fun main() {
    val numbers = arrayOf(1, 2, 3, 4, 5)

    // Print all elements
    numbers.forEach { println(it) }

    // Modify and print the array
    numbers[2] = 10
    println(numbers.joinToString())
}

Output

1
2
3
4
5
1, 2, 10, 4, 5

2. Using Array Constructor :The constructor takes the size of the array and a lambda function to initialize the elements.

Syntax

val num = Array(3, {i-> i*1})

Example

fun main()
{
	val arrayname = Array(5, { i -> i * 1 })
	for (i in 0..arrayname.size-1)
	{
		println(arrayname[i])
	}
}

Output

0
1
2
3
4

3. Typed Arrays: Kotlin provides specialized classes for primitive arrays to avoid the overhead of boxing.

Syntax:

val num = Array(3) { i -> i * 1 }

Example

fun main() {
    // Creating an IntArray of size 5, initialized with index * 2
    val intArray = IntArray(5) { it * 2 }

    // Creating a DoubleArray of size 3, initialized with index + 0.5
    val doubleArray = DoubleArray(3) { it + 0.5 }

    // Creating a BooleanArray with predefined values
    val booleanArray = booleanArrayOf(true, false, true)

    // Printing the contents of each typed array
    println("IntArray: ${intArray.joinToString()}")
    println("DoubleArray: ${doubleArray.joinToString()}")
    println("BooleanArray: ${booleanArray.joinToString()}")
}

Output

1 2 3 4 5
10 20 30 40 50

Accessing Array Elements

1. Using indexing : In Kotlin, array elements can be accessed using indexing. This involves specifying the position of the element within the array using its index. Array indices start at 0, so the first element is accessed with index 0, the second with index 1, and so on. Indexing is a straightforward way to retrieve or modify individual elements of an array.

Syntax:

val element = array[index]

Example

fun main() {
    // Define an array of integers
    val numbers = arrayOf(10, 20, 30, 40, 50)

    // Access elements using indexing
    val firstElement = numbers[0]   // Access the first element
    val secondElement = numbers[1]  // Access the second element
    val lastElement = numbers[4]    // Access the last element

    // Print the accessed elements
    println("First element: $firstElement")
    println("Second element: $secondElement")
    println("Last element: $lastElement")
}

Output:

First element: 10
Second element: 20
Last element: 50

2. Modifying Elements: Modifying elements in an array means changing the value of an element at a specific index. In an array, you can update any element by accessing it through its index and assigning a new value to that position. The array’s length and structure remain the same, but the value at the chosen index is replaced.

Syntax:

array[index] = new_value

Example

fun main() {
    // Define an array
    val arr = arrayOf(5, 10, 15, 20, 25)

    // Modify the element at index 1 (second element)
    arr[1] = 12

    // Modify the last element using a negative-like index (-1 is the last element)
    arr[arr.size - 1] = 30

    // Print the updated array
    println("Updated array: ${arr.joinToString(", ")}")
}

Output:

Updated array: 5, 12, 15, 20, 30

Array Methods:

1. Size: In Kotlin, the size property returns the number of elements in an array. This is useful when you want to know how many items are stored in the array. It is not a method but a property that gives you the length of the array.

Syntax:

array.size

Example

fun main() {
    // Define an array
    val arr = arrayOf(1, 2, 3, 4, 5)

    // Get the size of the array
    val arraySize = arr.size

    // Print the size
    println("The size of the array is: $arraySize")
}

Output:

The size of the array is: 5

2. Iterating Over an Array: Iterating over an array refers to accessing each element of the array one by one in sequence. It allows you to perform operations on each element. In Kotlin, this can be done using a for loop or the forEach function, both of which are commonly used to traverse an array.

Syntax:

for (element in array) {
    // Perform an operation with each element
}

Example

fun main() {
    // Define an array
    val arr = arrayOf(10, 20, 30, 40, 50)

    // Iterate over the array
    for (element in arr) {
        println(element)
    }
}

Output:

10
20
30
40
50

3. Using Higher-Order Functions: Higher-order functions in Kotlin are functions that take other functions as parameters or return functions. These are commonly used to perform operations on collections or arrays. Functions like mapfilterforEach, etc., are examples of higher-order functions that allow functional-style processing of array elements.

Syntax:

array.functionName { element ->
    // Perform an operation with each element
}

Example

fun main() {
    // Define an array
    val arr = arrayOf(1, 2, 3, 4, 5)

    // Use higher-order function map to create a new array with doubled values
    val doubledArray = arr.map { it * 2 }

    // Print the new array
    println(doubledArray)
}

Output:

[2, 4, 6, 8, 10]
End of lesson.