Kotlin – Check if String is Empty

Check if string is empty in Kotlin

To check if a given string is empty in Kotlin, you can call isEmpty() function on the given string object.

str.isEmpty()

The function returns a boolean value of true if the string is empty, or false if not. We can use this as a condition in the if-else statement, as shown in the following.

if ( str.isEmpty() ) {
    // string is empty
} else {
    // string is not empty
}

Examples

Check if given string is empty

In the following program, we take an empty string in str and programmatically check if this string value is empty or not using String.isEmpty() function.

Kotlin Program

fun main() {
    val str = ""
    if ( str.isEmpty() ) {
        println("The string is empty.")
    } else {
        println("The string is not empty.")
    }
}

Output

The string is empty.

Check if “Hello World” is empty

In the following program, let us take “Hello World” in the string variable str, and check the result of String.isEmpty() function. Since the string is not empty, else-block must execute.

Kotlin Program

fun main() {
    val str = "Hello World"
    if ( str.isEmpty() ) {
        println("The string is empty.")
    } else {
        println("The string is not empty.")
    }
}

Output

The string is not empty.