This article will explore various ways to convert int to string in java with example programs and their explanations.

Method 1: Using Integer.toString()
java.lang.Integer class has a toString() method. This method accepts an int value as argument and returns it as a string.
toString() is a static method, which means we do not need to create an object of Integer to invoke it. Example,

int num = 10;
// convert integer to string
String s = Integer.toString(num);

Method 2: Using String.valueOf()
java.lang.String class has a valueOf() method. This method accepts an int value as argument and returns it as string.
valueOf() is also static, thus, there is no need to create a string object. Example,

int num = 10;
// convert integer to string 
String s = String.valueOf(num);

Internally, valueOf() invokes Integer.toString().

Method 3: Using String.format()
format() method of String class returns a string as per the supplied values.
It takes 2 arguments:
1. format specifier of the value supplied as the second argument. For integer values, this value is %d.
2. Value to format. This is the integer value that needs to be converted to string.
Example,

int num = 10; 
// convert integer to string 
String s = String.format("%d", num);

For integers, you can also use %s as the format specifier in format() method.
Method 4: Using Integer.toUnsignedString()
This method works for only positive integers. toUnsignedString() takes two arguments.
First is the int value to be converted to String,
Second is the base or radix of the value to be converted.

For integer values, radix should be 10. Example,

int num = 10; 
// convert integer to string 
String s = Integer.toUnsignedString(num, 10);

Method 5: String concatenation
An integer value when concatenated with a string results in a string.
Thus, if the integer value is concatenated with an empty string, it is converted into a string, whose value is the same as the integer. Example,

int num = 10;
// add empty string to int value
String s = "" + num;

Method 6: Using DecimalFormat
java.text.DecimalFormat class provides options to format values. It has a format() method which accepts a long value and converts it to a string. Example,

int num = 10;
String str = new DecimalFormat().format(num);

Object of DecimalFormat can also be created using its static getInstance() method as shown below.

String format = DecimalFormat.getInstance().format(10);

Method 7: Using StringBuilder
Create an object of java.lang.StringBuilder and use its append() method with the int value. This will concatenate the int value to StringBuilder.
Finally, convert the StringBuilder to string value using its toString() method.

StringBuilder b = new StringBuilder();
int num = 10;
b.append(num);
String s = b.toString();

Hope the article was helpful.

0
Liked the article ? Spread the word...