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