In this tutorial, you shall learn how to check if given two strings are equal in Kotlin, using String.equals() function, with examples.

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.

</>
Copy
str1.equals(str2)

equals() method returns

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

Examples

1. Check if the two strings “abcd” and “abcd” 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

</>
Copy
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.

2. Check if the strings “abcd” and “apple” are equal – Negative scenario

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

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

    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.