How to convert a string to an integer and vice versa in Kotlin
How to convert a string to an integer and vice versa in Kotlin.
Here's a step-by-step tutorial on how to convert a string to an integer and vice versa in Kotlin.
Converting a String to an Integer
To convert a string to an integer in Kotlin, you can use the toInt() method. Here's how you can do it:
- Create a string variable that holds the string value you want to convert to an integer.
val str = "42"
- Convert the string to an integer using the
toInt()method.
val intValue = str.toInt()
The toInt() method parses the string and returns its corresponding integer value. If the string cannot be parsed as an integer, a NumberFormatException will be thrown.
val str = "Hello"
val intValue = str.toInt() // Throws NumberFormatException
- Use the converted integer value as needed.
println(intValue) // Output: 42
Converting an Integer to a String
To convert an integer to a string in Kotlin, you can use the toString() method. Here's how you can do it:
- Create an integer variable that holds the integer value you want to convert to a string.
val intValue = 42
- Convert the integer to a string using the
toString()method.
val str = intValue.toString()
The toString() method converts the integer value to its corresponding string representation.
- Use the converted string value as needed.
println(str) // Output: "42"
Handling Exceptions
When converting a string to an integer using toInt(), it's important to handle the NumberFormatException that can occur if the string cannot be parsed as an integer. You can use a try-catch block to handle the exception. Here's an example:
val str = "Hello"
try {
val intValue = str.toInt()
println(intValue)
} catch (e: NumberFormatException) {
println("Invalid input")
}
In this example, if the toInt() method throws a NumberFormatException, the catch block will be executed and "Invalid input" will be printed.
That's it! You now know how to convert a string to an integer and vice versa in Kotlin.