3

What are the alternative methods for converting and integer to a string?

whytheq
  • 34,466
  • 65
  • 172
  • 267
Selva
  • 839
  • 10
  • 25
  • 40
  • possible duplicate of [How to convert from int to String?](http://stackoverflow.com/questions/4105331/how-to-convert-from-int-to-string) – Sachin Jain Mar 06 '14 at 06:51

7 Answers7

10
Integer.toString(your_int_value);

or

your_int_value+"";

and, of course, Java Docs should be best friend in this case.

oezi
  • 51,017
  • 10
  • 98
  • 115
sfaiz
  • 303
  • 1
  • 8
  • 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
  • 1
    Implicit 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
String one = Integer.toString(1);
Thomas Lötzer
  • 24,832
  • 16
  • 69
  • 55
3
String myString = Integer.toString(myInt);
fredley
  • 32,953
  • 42
  • 145
  • 236
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
String.valueOf(anyInt);
Emil
  • 13,577
  • 18
  • 69
  • 108
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.