Challenge - 5 Problems
String to Number Conversion Master
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 converting string to integer?
Consider the following Kotlin code snippet that converts a string to an integer. What will be printed?
Kotlin
fun main() { val numberString = "1234" val number = numberString.toInt() println(number + 10) }
Attempts:
2 left
💡 Hint
Remember that toInt() converts the string to an integer number, so arithmetic operations work as expected.
✗ Incorrect
The string "1234" is converted to the integer 1234. Adding 10 results in 1244, which is printed.
❓ Predict Output
intermediate2:00remaining
What happens when converting a non-numeric string to Int in Kotlin?
What will happen when this Kotlin code runs?
Kotlin
fun main() { val invalidNumber = "abc" val number = invalidNumber.toInt() println(number) }
Attempts:
2 left
💡 Hint
Think about what happens if you try to convert a string that does not represent a number.
✗ Incorrect
The string "abc" cannot be converted to an integer, so Kotlin throws a NumberFormatException.
❓ Predict Output
advanced2:00remaining
What is the output of safe string to number conversion using toIntOrNull()?
What will this Kotlin program print?
Kotlin
fun main() { val input = "42a" val number = input.toIntOrNull() ?: -1 println(number) }
Attempts:
2 left
💡 Hint
toIntOrNull() returns null if conversion fails, so the Elvis operator ?: provides a default.
✗ Incorrect
Since "42a" is not a valid integer, toIntOrNull() returns null, so the default -1 is printed.
🧠 Conceptual
advanced2:00remaining
Which Kotlin function converts a string to a Double safely without throwing an exception?
Choose the Kotlin function that converts a string to a Double and returns null if the string is not a valid number.
Attempts:
2 left
💡 Hint
Look for the function that ends with 'OrNull' and works with Double type.
✗ Incorrect
toDoubleOrNull() tries to convert the string to Double and returns null if it fails, avoiding exceptions.
❓ Predict Output
expert2:00remaining
What is the output of this Kotlin code converting hexadecimal string to integer?
What will be printed by this Kotlin program?
Kotlin
fun main() { val hexString = "1A" val number = hexString.toInt(16) println(number) }
Attempts:
2 left
💡 Hint
toInt() can take a radix parameter to convert from different bases like hexadecimal.
✗ Incorrect
The string "1A" in base 16 equals decimal 26, so 26 is printed.