0
0
JavaHow-ToBeginner · 2 min read

Java How to Convert int to String Easily

In Java, you can convert an int to a String by using String.valueOf(intValue) or Integer.toString(intValue).
📋

Examples

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

How to Think About It

To convert an int to a String, think of turning a number into words you can read. Java provides built-in methods like String.valueOf and Integer.toString that take the number and give back its text form.
📐

Algorithm

1
Take the integer value you want to convert.
2
Use a built-in method like String.valueOf or Integer.toString to convert it.
3
Return or use the resulting String.
💻

Code

java
public class IntToString {
    public static void main(String[] args) {
        int number = 123;
        String str1 = String.valueOf(number);
        String str2 = Integer.toString(number);
        System.out.println(str1);
        System.out.println(str2);
    }
}
Output
123 123
🔍

Dry Run

Let's trace converting the int 123 to a String using String.valueOf.

1

Start with int number

number = 123

2

Convert using String.valueOf

str1 = String.valueOf(123) -> "123"

3

Print the String

Output: 123

StepVariableValue
1number123
2str1"123"
3output123
💡

Why This Works

Step 1: Using String.valueOf

The method String.valueOf(int) converts the integer to its string form by creating a new String representing the number.

Step 2: Using Integer.toString

The method Integer.toString(int) does the same by returning the string representation of the integer.

🔄

Alternative Approaches

Concatenation with empty string
java
public class IntToStringConcat {
    public static void main(String[] args) {
        int number = 123;
        String str = number + "";
        System.out.println(str);
    }
}
This is a quick trick but less clear than using built-in methods.

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

Time Complexity

Conversion takes constant time since it just formats the integer into characters.

Space Complexity

Space depends on the number of digits in the integer, as the string stores each digit.

Which Approach is Fastest?

All methods run in constant time; concatenation is simple but less explicit than built-in methods.

ApproachTimeSpaceBest For
String.valueOf(int)O(1)O(n)Clear and standard conversion
Integer.toString(int)O(1)O(n)Explicit integer to string conversion
Concatenation with ""O(1)O(n)Quick trick but less readable
💡
Use String.valueOf() for clear and safe int to String conversion.
⚠️
Trying to cast int to String directly like (String) intValue which causes errors.