0
0
Kotlinprogramming~20 mins

String type and immutability in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
String Mastery in Kotlin
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?

Consider the following Kotlin code snippet:

val original = "hello"
val modified = original.replace('h', 'j')
println(original)
println(modified)

What will be printed?

Kotlin
val original = "hello"
val modified = original.replace('h', 'j')
println(original)
println(modified)
Ahello\njello
Bhello\nhello
Cjello\njello
Djello\nhello
Attempts:
2 left
💡 Hint

Remember that Kotlin strings are immutable. The replace function returns a new string.

🧠 Conceptual
intermediate
1:30remaining
Why are Kotlin strings immutable?

Which of the following is the main reason Kotlin strings are immutable?

ATo allow strings to be changed in place without creating new objects
BTo make strings mutable and faster to change
CTo prevent strings from being used in collections
DTo allow strings to be safely shared between threads without synchronization
Attempts:
2 left
💡 Hint

Think about thread safety and performance.

🔧 Debug
advanced
2:00remaining
What error does this Kotlin code produce?

Examine this Kotlin code:

var text = "hello"
text[0] = 'j'
println(text)

What error will this code cause?

Kotlin
var text = "hello"
text[0] = 'j'
println(text)
AError: Val cannot be reassigned
BError: Unresolved reference to 'text'
CError: String cannot be assigned to by index
DNo error, prints 'jello'
Attempts:
2 left
💡 Hint

Think about whether Kotlin strings allow changing characters by index.

🚀 Application
advanced
2:30remaining
How to create a new string with a changed first character?

You want to change the first character of a Kotlin string str to 'J'. Which code snippet correctly does this?

Aval newStr = "J" + str.substring(1)
Bstr[0] = 'J'; val newStr = str
Cval newStr = str.replaceAt(0, 'J')
Dval newStr = str.setCharAt(0, 'J')
Attempts:
2 left
💡 Hint

Remember strings are immutable, so you must create a new string.

Predict Output
expert
3:00remaining
What is the output of this Kotlin code involving string references?

Consider this Kotlin code:

val a = "test"
val b = a
val c = b.replace('t', 'b')
println(a)
println(b)
println(c)

What will be printed?

Kotlin
val a = "test"
val b = a
val c = b.replace('t', 'b')
println(a)
println(b)
println(c)
Abest\nbest\nbesb
Btest\ntest\nbesb
Ctest\ntest\ntest
Dtest\nbest\nbesb
Attempts:
2 left
💡 Hint

Remember that b is just a reference to a, and strings are immutable.