Challenge - 5 Problems
StringBuilder Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Kotlin code using StringBuilder?
Consider the following Kotlin code snippet. What will it print?
Kotlin
fun main() { val sb = StringBuilder() for (i in 1..3) { sb.append(i) sb.append(",") } println(sb.toString()) }
Attempts:
2 left
💡 Hint
Look carefully at what is appended inside the loop.
✗ Incorrect
The loop appends the number and then a comma each time, so the output ends with a comma after the last number.
❓ Predict Output
intermediate2:00remaining
What is the final string length after these StringBuilder operations?
Given this Kotlin code, what is the length of the string in sb after execution?
Kotlin
fun main() { val sb = StringBuilder("Hello") sb.append(" World") sb.delete(5, 6) println(sb.length) }
Attempts:
2 left
💡 Hint
Deleting one character reduces length by one.
✗ Incorrect
Initial string "Hello" has length 5, appending " World" adds 6 characters (including space), total 11. Deleting one character reduces length to 10.
🔧 Debug
advanced2:00remaining
Why does this Kotlin code throw an exception?
This Kotlin code throws an exception. What is the cause?
Kotlin
fun main() { val sb = StringBuilder("abc") sb.delete(1, 5) println(sb.toString()) }
Attempts:
2 left
💡 Hint
Check the valid range for delete method indices.
✗ Incorrect
The delete method throws StringIndexOutOfBoundsException if the end index is greater than the current length of the StringBuilder.
🧠 Conceptual
advanced2:00remaining
Why is StringBuilder preferred over String concatenation in loops?
Which option best explains why using StringBuilder is better than using String concatenation inside loops in Kotlin?
Attempts:
2 left
💡 Hint
Think about how strings are stored and changed in memory.
✗ Incorrect
Strings are immutable in Kotlin, so concatenation creates new objects each time. StringBuilder changes the string content without creating new objects, improving performance.
❓ Predict Output
expert2:00remaining
What is the output of this Kotlin code using StringBuilder and insert?
Analyze this Kotlin code and select the exact output it produces.
Kotlin
fun main() { val sb = StringBuilder("Kotlin") sb.insert(3, " is") sb.insert(0, "I think") println(sb.toString()) }
Attempts:
2 left
💡 Hint
Remember insert shifts characters to the right.
✗ Incorrect
First insert adds " is" at index 3: "Kot islin". Then insert "I think" at index 0 shifts everything right, resulting in "I thinkKot islin".