How to convert Java int to String
In Java, we can convert int
into a String in two ways:
There are some alternative methods like String.format()
method, string concatenation operator etc that can also be used.
1. By using String.valueOf()
method
The valueOf() method is a part of String Class. It is a static method that converts an int value into a String value.
Example 1:
Here the int value passed in the method is converted into a String.
public class Main
{
public static void main(String args[])
{
int n = 500;
System.out.println("The int value is " +n);
String s = String.valueOf(n);
System.out.println("The string value is " +s);
}
}
The int value is 500
The string value is 500
2. By using Integer.toString()
method
The toString() method is a part of Integer Class. It is a static method that can also be used to convert int value to String.
Example 2:
Here, an int value is passed in the toString()
method to get a String
value.
public class Main
{
public static void main(String args[])
{
int n = 500;
System.out.println("The int value is " +n);
String s = Integer.toString(n);
System.out.println("The string value is " +s);
}
}
The int value is 500
The string value is 500
3. By using String.format()
method
The format() method is a part of the String class and is used to format the given arguments in a String.
Example 3:
Here, an int value is passed in the format()
method to get a String
value.
public class Studytonight
{
public static void main(String args[])
{
int n = 500;
System.out.println("The int value is " +n);
String s = String.format("%d",n);
System.out.println("The string value is " +s);
}
}
The int value is 500
The string value is 500
4. By using +
operator (concatenation)
We can use +
operator to concate any value to a string. The +
operator returns a String
object after concatenation. See the example below.
Example 4:
Here, an int
value is concatenated with an emty string to convert int to a String
.
public class Studytonight
{
public static void main(String args[])
{
int n = 500;
System.out.println("The int value is " +n);
String s = "" + n;
System.out.println("The string value is " +s);
}
}
The int value is 500
The string value is 500