Consider the following Kotlin code snippet:
val original = "hello"
val modified = original.replace('h', 'j')
println(original)
println(modified)What will be printed?
val original = "hello" val modified = original.replace('h', 'j') println(original) println(modified)
Remember that Kotlin strings are immutable. The replace function returns a new string.
The replace function does not change the original string. It returns a new string with replacements. So original remains "hello" and modified is "jello".
Which of the following is the main reason Kotlin strings are immutable?
Think about thread safety and performance.
Immutable strings can be shared safely between threads without locks, improving performance and safety.
Examine this Kotlin code:
var text = "hello" text[0] = 'j' println(text)
What error will this code cause?
var text = "hello" text[0] = 'j' println(text)
Think about whether Kotlin strings allow changing characters by index.
Kotlin strings are immutable. You cannot assign a character to a specific index. This causes a compilation error.
You want to change the first character of a Kotlin string str to 'J'. Which code snippet correctly does this?
Remember strings are immutable, so you must create a new string.
Concatenating 'J' with the substring from index 1 creates a new string with the first character changed.
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?
val a = "test" val b = a val c = b.replace('t', 'b') println(a) println(b) println(c)
Remember that b is just a reference to a, and strings are immutable.
Both a and b refer to the same string "test". The replace creates a new string c with replacements. So a and b print "test", c prints "besb".