What are the alternative methods for converting and integer to a string?
7 Answers
Integer.toString(your_int_value);
or
your_int_value+"";
and, of course, Java Docs should be best friend in this case.
4 Comments
Vivien Barousse
your_edit_value + ""; causes the allocation of an extra empty string object, call Integer.toString(your_int_value) and concatenates both of them. 3 strings allocations where the first statement requires only one. The first one is faster.Sean Patrick Floyd
the seoncd version is awful. Java is not PHP or JavaScript.
Tadeusz Kopec for Ukraine
Implicit conversion to
String has a big downside. val1 + val2 + "" is very different from "" + val1 + val2sfaiz
yes, totally agree value+""; is not a good approach. i was just trying to mention different ways of doing that.
Here are all the different versions:
a) Convert an Integer to a String
Integer one = Integer.valueOf(1);
String oneAsString = one.toString();
b) Convert an int to a String
int one = 1;
String oneAsString = String.valueOf(one);
c) Convert a String to an Integer
String oneAsString = "1";
Integer one = Integer.valueOf(oneAsString);
d) Convert a String to an int
String oneAsString = "1";
int one = Integer.parseInt(oneAsString);
There is also a page in the Sun Java tutorial called Converting between Numbers and Strings.
Comments
There is Integer.toString() or you can use string concatenation where 1st operand is string (even empty): String snr = "" + nr;. This can be useful if you want to add more items to String variable.
1 Comment
Michał Niklas
I think both are useful. Example: if you want to convert some number to string in loop then you can use
new_name = old_name + i + ".txt" or new_name = old_name + Integer.toString(i) + ".txt". In this case I prefer shorter method.