0
0
KotlinHow-ToBeginner · 2 min read

Kotlin How to Convert Int to String Easily

In Kotlin, you can convert an Int to a String by calling the toString() method on the integer, like val str = number.toString().
📋

Examples

Input123
Output"123"
Input0
Output"0"
Input-456
Output"-456"
🧠

How to Think About It

To convert an integer to a string, think of it like writing a number on paper. You take the number and change it into text form. In Kotlin, this is done by using the toString() method, which turns the number into its text equivalent.
📐

Algorithm

1
Get the integer value you want to convert.
2
Call the <code>toString()</code> method on the integer.
3
Store or use the resulting string as needed.
💻

Code

kotlin
fun main() {
    val number: Int = 123
    val text: String = number.toString()
    println(text)
}
Output
123
🔍

Dry Run

Let's trace converting the integer 123 to a string.

1

Start with integer

number = 123

2

Convert to string

text = number.toString() -> "123"

3

Print result

Output: 123

StepValue
Initial number123
After toString()"123"
Printed output123
💡

Why This Works

Step 1: Using toString() method

The toString() method is built into Kotlin's Int type and converts the number into its string form.

Step 2: Result is a String

After calling toString(), the result is a String that represents the number as text.

Step 3: Printing the string

When printed, the string shows the number characters exactly as the original integer.

🔄

Alternative Approaches

String interpolation
kotlin
fun main() {
    val number: Int = 123
    val text: String = "$number"
    println(text)
}
This uses Kotlin's string templates to convert the integer to a string, which is concise and readable.
String constructor
kotlin
fun main() {
    val number: Int = 123
    val text: String = number.toString()
    println(text)
}
Using <code>toString()</code> is the standard and clear way; Kotlin does not have a direct String constructor for Int.

Complexity: O(1) time, O(n) space

Time Complexity

Converting an integer to a string takes constant time because it involves formatting a fixed-size number.

Space Complexity

The space needed depends on the number of digits in the integer, so it is proportional to the length of the string.

Which Approach is Fastest?

Both toString() and string interpolation are equally fast and efficient for this task.

ApproachTimeSpaceBest For
toString()O(1)O(n)Clear and standard conversion
String interpolationO(1)O(n)Concise and readable code
💡
Use toString() for clear and direct conversion of integers to strings in Kotlin.
⚠️
Trying to assign an Int directly to a String variable without conversion causes errors.