Example 1: Java Program to Convert int to string using valueOf()
class Main {
public static void main(String[] args) {
// create int variable
int num1 = 36;
int num2 = 99;
// convert int to string
// using valueOf()
String str1 = String.valueOf(num1);
String str2 = String.valueOf(num2);
// print string variables
System.out.println(str1); // 36
System.out.println(str2); // 99
}
}
In the above example, we have used the valueOf()
method of the String
class to convert the int
variables into string.
Note: This is the most preferred way of converting int
variables to string in Java.
Example 2: Java Program to Convert int to string using toString()
We can also convert the int
variable into string using the toString()
method of the Integer
class. For example,
class Main {
public static void main(String[] args) {
// create int variables
int num1 = 476;
int num2 = 78656;
// convert int to string
// using toString()
String str1 = Integer.toString(num1);
String str2 = Integer.toString(num2);
// print string variables
System.out.println(str1); // 476
System.out.println(str2); // 78656
}
}
In the above example, we have used the toString()
method of the Integer
class to convert the int
variables into string.
Here, Integer
is the wrapper class. To learn more, visit the Java Wrapper Class.
Example 3: Java Program to Convert int to String using + Operator
class Main {
public static void main(String[] args) {
// create int variables
int num1 = 3476;
int num2 = 8656;
// convert int to string
// using + sign
String str1 = "" + num1;
String str2 = "" + num2;
// print string variables
System.out.println(str1); // 3476
System.out.println(str2); // 8656
}
}
Notice the line,
String str1 = "" + num1;
Here, we are using the string concatenation operation to convert an integer into the string. To learn more, visit Java String concatenation.
Example 4: Java Program to Convert int to String using format()
class Main {
public static void main(String[] args) {
// create a int variable
int num = 9999;
// convert int to string using format()
String str = String.format("%d", num);
System.out.println(str); // 9999
}
}
Here, we have used the format()
method to format the specified int
variable into a string. To learn more about formatting string, visit Java String format().