0
0
Kotlinprogramming~10 mins

String to number conversion in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - String to number conversion
Start with String input
Call conversion function
Check if String is valid number
Convert to number
Use the number in code
End
The program takes a string, tries to convert it to a number, checks if conversion is valid, then uses the number or handles errors.
Execution Sample
Kotlin
val str = "123"
val num = str.toInt()
println(num + 10)
Converts string "123" to integer 123 and adds 10, then prints 133.
Execution Table
StepActionExpressionResultNotes
1Assign stringstr = "123""123"String variable holds "123"
2Convert string to intnum = str.toInt()123String "123" converts to integer 123
3Add 10num + 10133Integer 123 plus 10 equals 133
4Print resultprintln(133)133Output is printed to console
💡 Conversion succeeds because "123" is a valid integer string
Variable Tracker
VariableStartAfter Step 2After Step 3Final
str"123""123""123""123"
numundefined123123123
Key Moments - 2 Insights
What happens if the string is not a valid number?
If the string is not a valid number, calling toInt() throws a NumberFormatException. This is shown by the check in step 3 of the concept flow where invalid input leads to error.
Why do we need to convert the string before adding 10?
Adding 10 to a string would concatenate it as text, not add numerically. Conversion to int changes the type so arithmetic works, as shown in step 3 of the execution table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'num' after step 2?
A123
B"123"
Cundefined
D133
💡 Hint
Check the 'Result' column in row for step 2 in execution_table
At which step is the string converted to a number?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Action' column in execution_table for conversion
If the string was "abc", what would happen at step 2?
Anum becomes 0
BProgram throws NumberFormatException
Cnum becomes "abc"
Dnum becomes null
💡 Hint
Refer to key_moments about invalid string conversion
Concept Snapshot
String to number conversion in Kotlin:
- Use toInt(), toDouble(), etc. to convert strings
- Conversion throws error if string is invalid
- Convert before arithmetic to get numeric results
- Handle exceptions for safe conversion
Full Transcript
This example shows how Kotlin converts a string "123" to an integer using toInt(). The program assigns the string, converts it to number, adds 10, and prints 133. If the string is invalid, toInt() throws an error. Conversion is necessary to perform arithmetic instead of string concatenation.