0
0
Kotlinprogramming~5 mins

String comparison (equals, compareTo) in Kotlin

Choose your learning style9 modes available
Introduction

We compare strings to check if they are the same or to find their order. This helps us decide if two words match or which one comes first.

Checking if a user typed the correct password.
Sorting a list of names alphabetically.
Finding if two words are exactly the same in a game.
Comparing input text to a stored value.
Deciding which string should appear first in a list.
Syntax
Kotlin
val resultEquals: Boolean = string1.equals(string2)
val resultCompare: Int = string1.compareTo(string2)

equals() returns true if strings are exactly the same.

compareTo() returns 0 if strings are equal, a negative number if the first string comes before the second, and a positive number if it comes after.

Examples
Checks if two strings are exactly the same.
Kotlin
val a = "apple"
val b = "apple"
println(a.equals(b))  // true
Since "apple" comes before "banana", compareTo returns a negative number.
Kotlin
val a = "apple"
val b = "banana"
println(a.compareTo(b))  // negative number
equals() is case sensitive. compareTo() also considers case when comparing.
Kotlin
val a = "apple"
val b = "Apple"
println(a.equals(b))  // false
println(a.compareTo(b))  // positive or negative depending on case
Sample Program

This program compares strings using equals() and compareTo(). It shows how case affects the results.

Kotlin
fun main() {
    val word1 = "Kotlin"
    val word2 = "kotlin"
    val word3 = "Kotlin"

    println("word1 equals word2: ${word1.equals(word2)}")
    println("word1 equals word3: ${word1.equals(word3)}")

    println("word1 compareTo word2: ${word1.compareTo(word2)}")
    println("word2 compareTo word1: ${word2.compareTo(word1)}")
    println("word1 compareTo word3: ${word1.compareTo(word3)}")
}
OutputSuccess
Important Notes

equals() is case sensitive. Use equalsIgnoreCase() if you want to ignore case.

compareTo() returns an integer showing order, not just true or false.

Negative result means first string is before second; positive means after.

Summary

Use equals() to check if two strings are exactly the same.

Use compareTo() to find the order between two strings.

Both methods consider uppercase and lowercase letters as different.