How do I convert an integer variable to a string variable in Java?
Asked
Active
Viewed 9.3k times
5 Answers
28
you can either use
String.valueOf(intVarable)
or
Integer.toString(intVarable)

Shijilal
- 2,175
- 10
- 32
- 55
10
There are at least three ways to do it. Two have already been pointed out:
String s = String.valueOf(i);
String s = Integer.toString(i);
Another more concise way is:
String s = "" + i;
See it working online: ideone
This is particularly useful if the reason you are converting the integer to a string is in order to concatenate it to another string, as it means you can omit the explicit conversion:
System.out.println("The value of i is: " + i);

Mark Byers
- 811,555
- 193
- 1,581
- 1,452
-
Does this really work? :o 'i' is an int i presume. huh i'm gonna have to try that out later. – Holly Jan 30 '11 at 11:13
-
@Holly: Yes, it might seem surprising that you can do this in a type-safe language like Java but it does actually work. See the ideone link I've posted. – Mark Byers Jan 30 '11 at 11:18
1
Here is the method manually convert the int to String value.Anyone correct me if i did wrong.
/**
* @param a
* @return
*/
private String convertToString(int a) {
int c;
char m;
StringBuilder ans = new StringBuilder();
// convert the String to int
while (a > 0) {
c = a % 10;
a = a / 10;
m = (char) ('0' + c);
ans.append(m);
}
return ans.reverse().toString();
}

Jegan
- 129
- 3
0
There are many different type of wat to convert Integer value to string
// for example i =10
1) String.valueOf(i);//Now it will return "10"
2 String s=Integer.toString(i);//Now it will return "10"
3) StringBuilder string = string.append(i).toString();
//i = any integer nuber
4) String string = "" + i;
5) StringBuilder string = string.append(i).toString();
6) String million = String.format("%d", 1000000)

Hoque MD Zahidul
- 10,560
- 2
- 37
- 40