How to Convert Integer to String in Java

How to Convert int to String in Java

It is used when you want to convert an integer to String. You can convert int to String by using the following methods:

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

Using String.valueOf() method

String.valueOf() method takes an integer value as an argument and returns a String representing the int argument. This method converts int to String. The valueOf() is the static method of String class. This is a very popular method to convert int to String. The signature of the valueOf() method is given below:

public static String.valueOf(int i)

Where i is an integer that needs to be converted into a String.

Example-

In the following example, sum is a variable of type integer having value 45.  str is the variable of type String that stores string value of integer variable sum i.e. 45. valueOf(sum) is the method that contain sum as an argument.  The first println statement prints the converted value of integer i.e”45”. The second println statement “123” is concatenated to the string “45” that prints “12345”.

Output-

Using Integer.toString() method

Integer.toString() method works same as String.valueOf() method. It belongs to the Integer class. It converts the specified integer value to String. The toString() is the static method that returns String representing the integer. A new instance of Integer class is created before conversion is performed. The signature of the toString() method is given below:

Where i is an integer variable that requires conversion.

Example-

In the following example, var is the variable of type integer having value 22. In the sixth line, str is a variable of type String that stores the converted value of an integer variable var, i.e, “22”. Integer is a wrapper class under the java.lang package. toString(var) is the method that contains an argument which we want to convert into String, i.e. var.

The first println statement prints the value of str i.e. “22”. Next println statement prints the concatenated string i.e. “3322”. The last println statement prints the value 66 because it adds the 44 into 22.

Output:

Using String.format() method

This method is used for formatting the String. By using this method, you can concatenate and format the output of the concatenated string at the same time. It is first introduced in JDK 5. The signature of String.format() method is given below.

public static String format(String format, Object… args)

Example-

In the following example, avg is a variable of type int having value 99. In the next line, str is a variable of type String that stores the converted value of integer variable avg. %d is the format specifier, avg is an argument. The println statement prints the “99” as a string.

Output: