Kotlin – Check if Two Strings are Equal

To check if two strings are equal in Kotlin, use String.equals() method.

Given two strings str1 and str2, and if we would like to check if the string str1 is equal to string str2, call equals() method on string str1 and pass the string str2 as argument to the method as shown below.

str1.equals(str2)

equals() method returns

  • true, if str1 equals str2
  • false if str1 is not equal to str2

Example 1 – Two Strings are Equal

In this example, we will take two strings in str1 and str2, such that both have same string values. We shall check if these two strings are equal using equals() method and observe the result.

Kotlin Program

fun main(args: Array<String>) {
    val str1 = "abcd"
    val str2 = "abcd"

    val result = str1.equals(str2)

    println("Value returned by equals() : " + result)
    if ( result ) {
        println("The two strings are equal.")
    }
}

Output

Value returned by equals() : true
The two strings are equal.

Example 2 – Two Strings are Not Equal

In this example, we will take two strings in str1 and str2, such that str1 is not equal to str2. We shall check if these two strings are equal using equals() method and observe the result.

Kotlin Program

fun main(args: Array<String>) {
    val str1 = "abcd"
    val str2 = "abcdefg"

    val result = str1.equals(str2)

    println("Value returned by equals() : " + result)
    if ( result ) {
        println("The two strings are equal.")
    } else {
        println("The two strings are not equal.")
    }
}

Output

Value returned by equals() : false
The two strings are not equal.

Conclusion

In this Kotlin Tutorial, we learned how to check if two strings are equal using String.equals() method, with the help of Kotlin example programs.