This question already has an answer here:
-
Java int to String - Integer.toString(i) vs new Integer(i).toString()
11 answers
-
How do I convert from int to String?
19 answers
Given a number:
int number = 1234;
Which would be the \"best\" way to convert this to a string:
String stringNumber = \"1234\";
I have tried searching (googling) for an answer but no many seemed \"trustworthy\".
Integer class has static method toString() - you can use it:
int i = 1234;
String str = Integer.toString(i);
Returns a String object representing the specified integer. The argument is converted to signed decimal representation and returned as a string, exactly as if the argument and radix 10 were given as arguments to the toString(int, int) method.
Always use either String.valueOf(number)
or Integer.toString(number)
.
Using \"\" + number is an overhead and does the following:
StringBuilder sb = new StringBuilder();
sb.append(\"\");
sb.append(number);
return sb.toString();
This will do. Pretty trustworthy. : )
\"\"+number;
Just to clarify, this works and acceptable to use unless you are looking for micro optimization.
The way I know how to convert an integer into a string is by using the following code:
Integer.toString(int);
and
String.valueOf(int);
If you had an integer i, and a string s, then the following would apply:
int i;
String s = Integer.toString(i); or
String s = String.valueOf(i);
If you wanted to convert a string \"s\" into an integer \"i\", then the following would work:
i = Integer.valueOf(s).intValue();
This is the method which i used to convert the integer to string.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();
}
One that I use often:
Integer.parseInt(\"1234\");
Point is, there are plenty of ways to do this, all equally valid. As to which is most optimum/efficient, you\'d have to ask someone else.