Convert Integer to String in Java

Converting an Integer to a String in Java is very easy. In this post, we will learn to convert an Integer to a String in two ways:

  • Using String.valueOf() method and
  • Using Integer.toString() method

Using String.valueOf()

The syntax of String.valueOf() method is given below:

String.valueOf(int intValue);

The String.valueOf() method returns the String as output. So, when we use this method the equivalent of an integer value given as a parameter will be converted to String. Let’s see an example below to understand it clearly:

int id = 12;

To convert this integer id to a String we use the following code:

String idString = String.valueOf(id);

This code will print the String equivalent of the integer id.

Using Integer.toString()

The toString() method is available in every object. Hence, if we have an Integer variable then we can easily convert it to a String. See the example below:

Integer idObject = 12;
String idString = idObject.toString();

Note

The drawback of using the toString() method is that when the object is null then it will throw a NullPointerException. To avoid this, it is best practice to use String.valueOf() method instead. If we use the String.valueOf() method, it returns the null as the converted output instead of throwing NullPointerException.
Sharing Is Caring: