How do I convert an integer variable to a string variable in Java?
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();
}
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);
Integer yourInt;
yourInt = 3;
String yourString = yourInt.toString();
you can either use
String.valueOf(intVarable)
or
Integer.toString(intVarable)
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)