0
0
Kotlinprogramming~20 mins

String comparison (equals, compareTo) in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
String Comparison Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Kotlin code comparing strings with equals()?
Consider the following Kotlin code snippet. What will it print?
Kotlin
fun main() {
    val a = "Hello"
    val b = "hello"
    println(a.equals(b))
    println(a.equals(b, ignoreCase = true))
}
Atrue\ntrue
Bfalse\ntrue
Cfalse\nfalse
Dtrue\nfalse
Attempts:
2 left
💡 Hint
Remember that equals() is case-sensitive by default unless ignoreCase is true.
Predict Output
intermediate
2:00remaining
What does compareTo() return when comparing "apple" and "banana"?
What is the output of this Kotlin code?
Kotlin
fun main() {
    val result = "apple".compareTo("banana")
    println(result)
}
AA negative number less than -1
B0
C1
D-1
Attempts:
2 left
💡 Hint
compareTo returns a negative number if the first string is lexicographically less than the second.
🔧 Debug
advanced
2:00remaining
What error does this Kotlin code produce?
Examine this Kotlin code and identify the error it causes.
Kotlin
fun main() {
    val s1: String = null
    val s2 = "test"
    println(s1.equals(s2))
}
APrints false without error
BRuntimeException: NullPointerException
CCompilation error: Unresolved reference: equals
DCompilation error: Null can not be a value of a non-null type String
Attempts:
2 left
💡 Hint
In Kotlin, variables must be declared nullable to hold null.
Predict Output
advanced
2:00remaining
What is the output of this Kotlin code using compareTo with ignoreCase?
What will this Kotlin program print?
Kotlin
fun main() {
    val s1 = "Kotlin"
    val s2 = "kotlin"
    println(s1.compareTo(s2, ignoreCase = true))
    println(s1.compareTo(s2))
}
A-32\n0
B0\n32
C0\n-32
D32\n0
Attempts:
2 left
💡 Hint
compareTo returns 0 if strings are equal ignoring case, otherwise a positive or negative number.
🧠 Conceptual
expert
2:00remaining
How many items are in the resulting map after this Kotlin code?
What is the size of the map produced by this Kotlin code?
Kotlin
fun main() {
    val keys = listOf("a", "A", "b", "B")
    val map = keys.associateWith { it.lowercase() }
    val filteredMap = map.filterKeys { it.equals(it.lowercase(), ignoreCase = true) }
    println(filteredMap.size)
}
A4
B2
C3
D1
Attempts:
2 left
💡 Hint
Check which keys equal their lowercase version ignoring case.