English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program to check if a string is empty or null

Comprehensive Collection of Kotlin Examples

In this program, you will learn to use if in Kotlin-else statement and function to check if the string is empty or null.

Example1:Check if the string is empty or null

fun main(args: Array<String>) {
    : String? = null1: String? = null
    : String? = null2 "
    if (isNullOrEmpty(str1))
        println("str1is null or empty.
    else
        println("str1is not null or empty."
    if (isNullOrEmpty(str2))
        println("str2is null or empty."
    else
        println("str2is not null or empty."
}
fun isNullOrEmpty(str: String?): Boolean {
    if (str != null && !str.isEmpty())
        return false
    return true
}

When the program is run, the output is:

str1Is null or empty.
str2Is null or empty.

In the above program, we have two strings str1and str2.str1contains null value, str2is an empty string.

We also created a function isNullOrEmpty(), as the name suggests, which checks if a string is null or empty. It uses != null and the string's isEmpty() method for null checking to perform the check

In simple terms, if a string is not null and isEmpty() returns false, then it is neither null nor empty. Otherwise, it is.

However, if the string only contains whitespace characters (spaces), the above program will not return empty. Technically, isEmpty() finds that it contains spaces and returns false. For strings with spaces, we use the string method trim() to trim all leading and trailing whitespace characters.

Example2:Check if a string with spaces is empty or not empty

fun main(args: Array<String>) {
    : String? = null1: String? = null
    : String? = null2 val str
    if (isNullOrEmpty(str1))
        println("str1is null or empty."
    else
        println("sstr2is not null or empty."
    if (isNullOrEmpty(str2))
        println("str2is null or empty."
    else
        println("str2is not null or empty."
}
fun isNullOrEmpty(str: String?): Boolean {
    if (str != null && !str.trim().isEmpty())
        return false
    return true
}

When the program is run, the output is:

str1Is null or empty.
str2Is null or empty.

In isNullorEmpty(), we added an additional trim() method that removes all leading and trailing whitespace characters from the given string.
If the string contains only spaces, the function returns true.

This is the equivalent Java code:Java Program to Check If a String Is Null or Empty.

Comprehensive Collection of Kotlin Examples