What's the Kotlin equivalent of Java's String[]?

AndroidMobile DevelopmentApps/ApplicationsKotlin

String is a collection which is implemented using String class. As per the Kotlin documentation, a string can be defined as follows −

Class String : Comparable<String>, CharSequence

In Kotlin, a string is a collection of characters. Strings are immutable in nature which means they are read-only. The length and elements of a string can be modified once declared.

In Java, we have an option to create an empty String array by defining it like String[]. In this article, we will see how we can achieve the same using Kotlin library function.

Example: Using arrayOf()

Kotlin library provides a function to create an array of different types of Strings. In this example, we will create an array of Strings using arrayOf().

Example

fun main(args: Array<String>) {

   var myEmptyStringArray = arrayOf<String>()

   println(myEmptyStringArray)

}

Output

It will generate the following output −

[Ljava.lang.String;@4aa298b7

In the above piece of code, we have declared an empty array of Strings and named it as "myEmptyStringArray" and we have printed its contents. It generates the hash code of the memory location.

Example: Using arrayOfNulls()

arrayOfNulls() is another function which creates an array of empty Strings. In the following example, we will modify our previous example and we will create an array of empty Strings.

Example

fun main(args: Array<String>) {

   var myEmptyStringArray: Array<String?> = arrayOfNulls(3)

   println(myEmptyStringArray)

}

Output

It will generate the following output −

[Ljava.lang.String;@4aa298b7

In the above piece of code, we have declared an empty array of Strings and named it as "myEmptyStringArray" and we have printed its contents. It generates the hash code of the memory location.

Example: Using emptyArray()

We can also use emptyArray() to create an empty array of Strings in Kotlin. In the following example, we will create an empty array of Strings using emptyArray().

Example

fun main(args: Array<String>) {
   var myEmptyStringArray: Array<String> = emptyArray()
   println(myEmptyStringArray)
}

Output

It will generate the following output −

[Ljava.lang.String;@4aa298b7
raja
Updated on 27-Oct-2021 11:14:17

Advertisements