English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, we will learn how to convert an integer (int) variable to a string in Java.
To understand this example, you should understand the followingJava programmingTopic:
class Main { public static void main(String[] args) { // Create an 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 the string variable System.out.println(str1); // 36 System.out.println(str2); // 99 } }
In the above example, we used the valueOf() method of the String class to convert the int variable to a string.
Note: This is the best way to convert int variables to strings in Java.
We can also use the toString() method of the class to convert the int variable to a string Integer. For example,
class Main { public static void main(String[] args) { // Create an int variable int num1 = 476; int num2 = 78656; // Convert int to string // Using toString() String str1 = Integer.toString(num1); String str2 = Integer.toString(num2); //Print the string variable System.out.println(str1); // 476 System.out.println(str2); // 78656 } }
In the above example, we used the toString() method of the Integer class to convert the int variable to a string.
Here, Integer is a wrapper class. For more information, please visitJava wrapper class.
class Main { public static void main(String[] args) { // Create an int variable int num1 = 3476; int num2 = 8656; //Convert int to string // using + sign String str1 = "" + num1; String str2 = "" + num2; //Print the string variable System.out.println(str1); // 3476 System.out.println(str2); // 8656 } }
Note this line,
String str1 = "" + num1;
Here, we use string concatenation to convert an integer to a string. For more information, please visitJava String Concatenation.
class Main { public static void main(String[] args) { // Create an int variable int num = 9999; //Using format() to convert int to string String str = String.format("%d", num); System.out.println(str); // 9999 } }
Here, we use the format() method to format a specified int variable into a string. For more information on string formatting, please visitJava String format().