Concatenating with an empty String
Easiest way to convert an int to a string is to concatenate int with an empty string. That will give you a string value, conversion is handled for you.
public class IntToString {
public static void main(String[] args) {
int num = 7;
String value = "" + num;
System.out.println("Value is " + value);
}
}
Output
Value is 7
Using valueOf() method of String class
String class has valueOf() method which is overloaded and those variants take int, float, double, long data types as paramters. Using valueOf(int i) method will return the string representation of the int argument.
public class IntToString {
public static void main(String[] args) {
int num = 7;
String value = String.valueOf(num);
System.out.println("Value is " + value);
}
}
Output
Value is 7
toString() method of the wrapper classes
Each of the Number subclasses (Integer, Float, Double etc.) includes a class method, toString(), that will convert its primitive type to a string. Thus, using Integer.toString(int i) returns a String object representing the specified integer.
public class IntToString {
public static void main(String[] args) {
int num = 7;
String value = Integer.toString(num);
System.out.println("Value is " + value);
}
}
Output
Value is 7
That's all for this topic Converting int to string - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like -