EN
Java - convert int to String
7
points
In Java, we can convert int to String in couple of different ways.
Short solutions:
// solution 1
String str1 = String.valueOf(123); // 123
// solution 2
String str2 = Integer.toString(123); // 123
// solution 3
String str3 = "" + 123; // 123
1. Using String.valueOf()
public class Example1 {
public static void main(String[] args) {
int num = 123;
String str = String.valueOf(num);
System.out.println(str); // 123
}
}
Output:
123
2. Using Integer.toString()
public class Example2 {
public static void main(String[] args) {
int num = 123;
String str = Integer.toString(num);
System.out.println(str); // 123
}
}
Output:
123
3. Using "" + 123
public class Example3 {
public static void main(String[] args) {
int num = 123;
String str = "" + num;
System.out.println(str); // 123
}
}
Output:
123
4. Using String.format()
public class Example4 {
public static void main(String[] args) {
int num = 123;
String str = String.format("%d", num);
System.out.println(str); // 123
}
}
Output:
123
5. Using StringBuilder
public class Example5 {
public static void main(String[] args) {
int num = 123;
StringBuilder sb = new StringBuilder();
sb.append(num);
String str = sb.toString();
System.out.println(str); // 123
}
}
Output:
123
The same can be applied to StringBuffer
6. Using DecimalFormat
import java.text.DecimalFormat;
public class Example6 {
public static void main(String[] args) {
int num = 123;
DecimalFormat df = new DecimalFormat("#");
String str = df.format(num);
System.out.println(str); // 123
}
}
Output:
123
7. Using DecimalFormat with floating point pattern
import java.text.DecimalFormat;
public class Example7 {
public static void main(String[] args) {
int num = 12345;
DecimalFormat df = new DecimalFormat("#,##0");
String str = df.format(num);
System.out.println(str); // 12,345
}
}
Output:
12,345
References
- Integer.toString(int)
- String.valueOf(int)
- String.format(java.lang.String,java.lang.Object...)
- StringBuilder.append(int)
- DecimalFormat.format(long)
- Type conversion - wik
Post summary image