Java program to convert int type variables to string
In Java, you can convert an int
type variable to a String
type variable using the String.valueOf()
method or by concatenating the int
value with an empty String
. Here are examples of both methods:
Method 1: Using the String.valueOf()
method
int num = 123; String str = String.valueOf(num); System.out.println("String value: " + str); // output: 123
In the above example, we define an int
variable num
with a value of 123. We then use the String.valueOf()
method to convert num
to a String
variable str
.
After the conversion, the value of str
is "123", which we verify by printing it to the console using the System.out.println
method.
Method 2: Concatenating the int
value with an empty String
int num = 456; String str = num + ""; System.out.println("String value: " + str); // output: 456
In the above example, we define an int
variable num
with a value of 456. We then concatenate num
with an empty String
to convert it to a String
variable str
.
After the conversion, the value of str
is "456", which we verify by printing it to the console using the System.out.println
method.
Note that the Integer.toString()
method can also be used to convert an int
variable to a String
variable, like this:
int num = 789; String str = Integer.toString(num); System.out.println("String value: " + str); // output: 789