How to Convert an Integer to a String in Java

Hassan Saeed Feb 02, 2024
  1. Use String.valueOf(number) to Convert Integer to String in Java
  2. Use String Concatenation to Convert Integer to String in Java
  3. Use Integer.toString(number) to Convert Integer to String in Java
  4. Conclusion
How to Convert an Integer to a String in Java

This tutorial discusses methods to convert an integer to a string in Java. A variable in Java serves as a storage unit and needs to be declared before usage. A typical declaration looks like this:

String x = "test";
int y = 0;

The value of a variable can be modified over time, but it is impossible to assign a value of a different data type or change the data type of the variable. For example:

int x = 5;
x = "test";

It will throw the following error:

> error: incompatible types: String cannot be converted to int
>	x = "test";

Similarly, if we try to re-assign the data type of an already declared variable:

int x = 5;
String x = "test";

It again would throw an error:

> error: variable x is already defined in method main(String[])
> 	String x = "test";

Now that we have a good understanding of how variables behave in Java, let us discuss how we can convert an integer to a string in Java. Given an integer:

int x = 1234;

We want to convert this value to a string and save it in a string variable:

String str_x = "1234";

Use String.valueOf(number) to Convert Integer to String in Java

String class in Java has several default methods. We will use String.valueOf(number) to convert an integer to a string.

public class MyClass {
  public static void main(String args[]) {
    int x = 5;
    String str_x = String.valueOf(x);
    System.out.println(str_x);
  }
}

Output:

5

Use String Concatenation to Convert Integer to String in Java

We can also use string concatenation to convert an integer value to a string: "" + number;

public class MyClass {
  public static void main(String args[]) {
    int x = 5;
    String str_x = "" + x;
    System.out.println(str_x);
  }
}

Output:

5

Use Integer.toString(number) to Convert Integer to String in Java

Integer class in Java also provides several default methods. We will use Integer.toString(number) to convert an integer value to a string.

public class MyClass {
  public static void main(String args[]) {
    int x = 5;
    String str_x = Integer.toString(x);
    System.out.println(str_x);
  }
}

Output:

5

Conclusion

We have discussed three different methods to convert an integer value to a string in Java. Although all the three ways work fine, it is a recommended practice to avoid string concatenation since it adds an overhead and is not as efficient as Integer.toString(number) or String.valueOf(number).

Related Article - Java String

Related Article - Java Int