public class Main {
public static void main(String[] args) {
int num = 123;
// convert int to String using Integer.toString()
String str = Integer.toString(num);
System.out.println("Number: " + num);
System.out.println("String: " + str);
}
}
This program uses the Integer.toString()
method to convert an int
variable num
to a String variable str
. The output of the program will be:
Number: 123
String: 123
Note that there are also other ways to convert an int
variable to a String
variable in Java, such as using the String.valueOf()
method or concatenation with an empty string.
public class Main {
public static void main(String[] args) {
// Initialize an int variable
int number = 42;
// Convert int to String using String.valueOf()
String strNumber = String.valueOf(number);
// Print both the int and String values
System.out.println("Int value: " + number);
System.out.println("String value: " + strNumber);
}
}
Int value: 42
String value: 42
public class Main {
public static void main(String[] args) {
// Initialize an int variable
int number = 42;
// Convert int to String using concatenation with an empty string
String strNumber = "" + number;
// Print both the int and String values
System.out.println("Int value: " + number);
System.out.println("String value: " + strNumber);
}
}
Output :
Int value: 42
String value: 42