What are the alternative methods for converting and integer to a string?
Asked
Active
Viewed 4.6k times
7 Answers
10
Integer.toString(your_int_value);
or
your_int_value+"";
and, of course, Java Docs should be best friend in this case.
-
2`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. – Vivien Barousse Sep 27 '10 at 10:09
-
the seoncd version is awful. Java is not PHP or JavaScript. – Sean Patrick Floyd Sep 27 '10 at 10:30
-
1Implicit conversion to `String` has a big downside. `val1 + val2 + ""` is **very** different from `"" + val1 + val2` – Tadeusz Kopec for Ukraine Sep 27 '10 at 11:45
-
yes, totally agree value+""; is not a good approach. i was just trying to mention different ways of doing that. – sfaiz Sep 27 '10 at 15:00
3
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.

Sean Patrick Floyd
- 292,901
- 67
- 465
- 588
2
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.

Michał Niklas
- 53,067
- 18
- 70
- 114
-
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. – Michał Niklas Dec 28 '10 at 17:09
0
You can use String.valueOf(thenumber)
for conversion. But if you plan to add another word converting is not nessesary. You can have something like this:
String string = "Number: " + 1
This will make the string equal Number: 1.