Kotlin – Check if two Strings are Equal

Check if two strings are equal in Kotlin

To check if given two strings are equal in Kotlin, you can use Equal-to == operator. Pass the two strings as operands to the Equal-to operator.

str1 == str2

This expression returns a boolean value of true if the two strings are equal, or false if not. We can use this expression as a condition in if-else statement.

Examples

Check if the strings “apple” and “apple” are equal

In the following program, we take a two string values in str1 and str2, and check if the string values in these two string variables are equal.

Kotlin Program

fun main() {
    val str1 = "apple"
    val str2 = "apple"

    if (str1 == str2) {
        print("Two strings are equal.")
    } else {
        print("Two strings are not equal.")
    }
}

Output

Two strings are equal.

Check if the strings “apple” and “banana” are equal

In the following program, we take a two string values in str1 and str2, and check if the string values in these two string variables are equal.

We have take the string values such that they are not equal. Therefore else-block must execute.

Kotlin Program

fun main() {
    val str1 = "apple"
    val str2 = "banana"

    if (str1 == str2) {
        print("Two strings are equal.")
    } else {
        print("Two strings are not equal.")
    }
}

Output

Two strings are not equal.