Bird
Raised Fist0
Kotlinprogramming~10 mins

String comparison (equals, compareTo) in Kotlin - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - String comparison (equals, compareTo)
Start
↓
Get two strings
↓
Use equals()
↓
Are strings exactly same?
Yes→Return true
↓
Return false
↓
Use compareTo()
↓
Compare lex order
↓
Return negative/zero/positive
↓
End
First, we check if two strings are exactly equal using equals(). Then, we compare their order lexicographically using compareTo(), which returns a number indicating their order.
Execution Sample
Kotlin
val a = "apple"
val b = "Apple"
println(a.equals(b))
println(a.compareTo(b))
This code compares two strings 'apple' and 'Apple' using equals() and compareTo(), printing the results.
Execution Table
StepActionEvaluationResult
1Assign a = "apple"a = "apple"a = "apple"
2Assign b = "Apple"b = "Apple"b = "Apple"
3Evaluate a.equals(b)"apple".equals("Apple")false
4Evaluate a.compareTo(b)"apple".compareTo("Apple")32
5Print equals resultfalseOutput: false
6Print compareTo result32Output: 32
💡 All steps completed, program ends after printing results.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
aundefined"apple""apple""apple"
bundefinedundefined"Apple""Apple"
Key Moments - 2 Insights
Why does equals() return false even though the words look similar?
equals() checks exact match including case. "apple" and "Apple" differ in uppercase 'A', so it returns false (see step 3 in execution_table).
What does the number 32 from compareTo() mean?
compareTo() returns a positive number because lowercase 'a' has a higher Unicode value than uppercase 'A'. The number 32 is the difference in their Unicode codes (see step 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result of a.equals(b) at step 3?
Atrue
Bfalse
Cnull
D32
💡 Hint
Check the 'Result' column at step 3 in execution_table.
At which step does the program print the compareTo() result?
AStep 4
BStep 5
CStep 6
DStep 3
💡 Hint
Look for the step where output shows 'Output: 32' in execution_table.
If we change b to "apple", what would a.equals(b) return?
Atrue
B32
Cfalse
Dnull
💡 Hint
Refer to how equals() works in key_moments and execution_table step 3.
Concept Snapshot
String comparison in Kotlin:
- Use equals() to check exact match (case-sensitive).
- Use compareTo() to get lexicographic order:
  returns 0 if equal,
  negative if first < second,
  positive if first > second.
- equals() returns Boolean, compareTo() returns Int.
Full Transcript
This example shows how Kotlin compares strings. First, two strings a and b are assigned values "apple" and "Apple". The equals() function checks if they are exactly the same, including case, and returns false because 'a' and 'A' differ. Then compareTo() compares their lexicographic order and returns 32, a positive number, because lowercase 'a' has a higher Unicode value than uppercase 'A'. The program prints false and 32 as results. This teaches that equals() is strict and case-sensitive, while compareTo() tells order by returning a number.

Practice

(1/5)
1. Which Kotlin method should you use to check if two strings have exactly the same characters and case?
val a = "Hello"
val b = "hello"
easy
A. a.equals(b)
B. a.compareTo(b)
C. a === b
D. a.equals(b, ignoreCase = true)

Solution

  1. Step 1: Understand equals() method

    The equals() method checks if two strings are exactly the same including case.
  2. Step 2: Compare equals() with other options

    compareTo() returns an order number, === checks reference equality (not content), equals(ignoreCase=true) ignores case, so only equals() matches exact case-sensitive check.
  3. Final Answer:

    a.equals(b) -> Option A
  4. Quick Check:

    Use equals() for exact string match [OK]
Hint: Use equals() for exact case-sensitive string match [OK]
Common Mistakes:
  • Using compareTo() to check equality
  • Assuming === checks content equality
  • Using equals(ignoreCase=true) when case matters
2. Which of the following is the correct syntax to compare two strings str1 and str2 for equality ignoring case in Kotlin?
easy
A. str1.equals(str2, ignoreCase = true)
B. str1.compareTo(str2, ignoreCase = true)
C. str1.equals(str2)
D. str1 == str2

Solution

  1. Step 1: Recall equals() with ignoreCase parameter

    In Kotlin, equals() can take ignoreCase=true to compare strings ignoring case differences.
  2. Step 2: Check other options

    A: equals() without ignoreCase is case-sensitive, B: compareTo(ignoreCase=true) returns Int not Boolean, D: == is case-sensitive.
  3. Final Answer:

    str1.equals(str2, ignoreCase = true) -> Option A
  4. Quick Check:

    Use equals(ignoreCase=true) to ignore case [OK]
Hint: Use equals(ignoreCase=true) to compare ignoring case [OK]
Common Mistakes:
  • Using compareTo(ignoreCase=true) directly (returns Int, not Boolean)
  • Using == which is case-sensitive
  • Forgetting to set ignoreCase=true
3. What will be the output of the following Kotlin code?
val s1 = "apple"
val s2 = "banana"
println(s1.compareTo(s2))
medium
A. A positive number
B. A negative number
C. 0
D. Compilation error

Solution

  1. Step 1: Understand compareTo() behavior

    compareTo() returns a negative number if the first string is lexicographically less than the second.
  2. Step 2: Compare "apple" and "banana" lex order

    "apple" comes before "banana" alphabetically, so compareTo returns a negative number.
  3. Final Answer:

    A negative number -> Option B
  4. Quick Check:

    "apple" < "banana" means compareTo() < 0 [OK]
Hint: compareTo() < 0 means first string is before second [OK]
Common Mistakes:
  • Assuming compareTo() returns boolean
  • Confusing positive and negative return values
  • Thinking compareTo() returns 0 for different strings
4. The following Kotlin code is intended to check if two strings are equal ignoring case, but it does not compile. What is the error?
val a = "Test"
val b = "test"
if (a.compareTo(b, ignoreCase = true)) {
println("Equal")
} else {
println("Not Equal")
}
medium
A. Missing parentheses in if condition
B. ignoreCase is not a valid parameter for compareTo()
C. Strings cannot be compared with compareTo()
D. compareTo() returns Int, cannot be used as Boolean

Solution

  1. Step 1: Check compareTo() return type

    compareTo() returns an Int, not a Boolean, so it cannot be used directly in if condition.
  2. Step 2: Understand how to check equality with compareTo()

    To check equality ignoring case, compareTo() == 0 should be used, not just compareTo() alone.
  3. Final Answer:

    compareTo() returns Int, cannot be used as Boolean -> Option D
  4. Quick Check:

    compareTo() returns Int, use == 0 to check equality [OK]
Hint: compareTo() returns Int; compare with 0 for equality [OK]
Common Mistakes:
  • Using compareTo() directly as Boolean
  • Forgetting to compare result with 0
  • Assuming ignoreCase is invalid parameter (it is valid)
5. You want to sort a list of strings ignoring case in Kotlin. Which code snippet correctly sorts the list val fruits = listOf("Banana", "apple", "Cherry") ignoring case?
hard
A. fruits.sortedBy { it }
B. fruits.sortedBy(String.CASE_INSENSITIVE_ORDER)
C. fruits.sortedWith(String.CASE_INSENSITIVE_ORDER)
D. fruits.sorted()

Solution

  1. Step 1: Understand sorting ignoring case

    To sort strings ignoring case, use a comparator that compares strings case-insensitively.
  2. Step 2: Check options for case-insensitive sorting

    A and D are case-sensitive. C: sortedBy expects key selector, not Comparator (compile error). B uses built-in case-insensitive Comparator correctly.
  3. Final Answer:

    fruits.sortedWith(String.CASE_INSENSITIVE_ORDER) -> Option C
  4. Quick Check:

    Use sortedWith(String.CASE_INSENSITIVE_ORDER) for case-insensitive sort [OK]
Hint: Use sortedWith(String.CASE_INSENSITIVE_ORDER) to ignore case in sort [OK]
Common Mistakes:
  • Using sorted() which is case-sensitive
  • Using sortedBy { it } which is case-sensitive
  • Confusing sortedBy (selector) with sortedWith (Comparator)
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard