531

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".

Anderson Green
  • 30,230
  • 67
  • 195
  • 328
Trufa
  • 39,971
  • 43
  • 126
  • 190
  • @lokesh I was taking a look at the valueOf implementation in the string class - http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/lang/String.java. toString will be called inside of String.valueOf. proxy in a sense. – committedandroider Oct 13 '19 at 16:25

6 Answers6

1020

There are multiple ways:

  • String.valueOf(number) (my preference)
  • "" + number (I don't know how the compiler handles it, perhaps it is as efficient as the above)
  • Integer.toString(number)
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • I'll give it a go! thank you! BTW I had read about concatenation, but for some reason it feels like a hack more that a solution (not a technical assessment) thanks!! – Trufa Feb 21 '11 at 20:45
  • 4
    @Trufa - I would use valueOf() out of these 3. – CoolBeans Feb 21 '11 at 20:52
  • I checked the source code (1.6.0.24 Sun) and the first and third options are basically identical. String.valueOf(int) delegates to Integer.toString(int) for radixes of 10. – brabec Feb 21 '11 at 22:41
  • 2
    @stoupa - yes, but you can use `String.valueOf(..)` with any argument. – Bozho Feb 21 '11 at 22:55
  • 1
    Are these three solutions "compiled" to one thing ? Or one of those is preferable ? – Paweł Brewczynski Jun 01 '13 at 23:16
  • 7
    they are practically the same (the last one invokes the first one, and the 2nd one is compiled to the first one). I prefer the 1st one – Bozho Jun 03 '13 at 09:39
  • 25
    @Bozho Your last comment is BACKWARDS. Actually, the first way invokes the last. (See String source in JDK at http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/lang/String.java?av=f .) – ingyhere Nov 16 '13 at 13:36
  • 1
    Notably, also, the first will not validate it is actually receiving an int versus some other primitive/type since the method is overloaded in String. From a type checking perspective, "Integer.toString()" is much better. – ingyhere Nov 16 '13 at 13:39
  • StringBuilder is also an option like http://javadevnotes.com/java-integer-to-string-examples – JavaDev Feb 15 '15 at 14:16
  • 4
    int oopsPitfall = 0700; String.valueOf(oopsPitfall); – JBA Apr 10 '15 at 07:54
  • 1
    `"" + number` uses `StringBuilder` as of JDK 7, `StringBuilder` uses `Integer.getChars` to convert the `int` into a `String`. It's not a good approach to use unless your already using a `StringBuilder`. – sixones Nov 19 '16 at 13:57
  • 3
    @jba If you add a zero before an integer, it is taken as an octal nonetheless. So what String.valueof() gives is actually right and is not a pitfall. – posixKing Apr 08 '17 at 02:11
  • 1
    Number 2 has a lot of extra overhead (it's equivalent to `new StringBuilder().append("").append(number).toString()`) – Solomon Ucko Jun 13 '17 at 21:40
  • 1
    I prefer option 3. It seems to be the most efficient approach, there's the compile time integer check and also if I want to convert "Integer to String", it sounds good to call "Integer.toString". – tomorrow Aug 12 '20 at 08:32
  • ```"" + number``` actually uses StringBuilder – Nano Nov 17 '22 at 08:23
65

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.

lukastymo
  • 26,145
  • 14
  • 53
  • 66
52

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();
Ankush soni
  • 1,439
  • 1
  • 15
  • 30
AllThatICode
  • 1,250
  • 13
  • 19
  • 1
    The bytecode compiler can't optimize that away? I would expect the optimizer to remove the sb.append(""). But I don't know much about compiler optimization in Java. – Gellweiler Nov 04 '21 at 16:45
  • It can. Java 11 compiler produces an invocation of `makeConcatWithConstants`. Some older releases used StringBuffer maybe. – Pavel Vlasov May 02 '23 at 12:04
45

This will do. Pretty trustworthy. : )

    ""+number;

Just to clarify, this works and acceptable to use unless you are looking for micro optimization.

Nishant
  • 54,584
  • 13
  • 112
  • 127
  • 6
    Thank you very much, this actually woks I don't like it though (nothing technical about my dislike) I just "feel" like it is a hack, not a real solution (probably not true). – Trufa Feb 21 '11 at 21:00
  • 2
    Your answer has a lot of extra overhead (it's equivalent to new StringBuilder().append("").append(number).toString()) – Solomon Ucko Jun 13 '17 at 21:41
  • @SolomonUcko may I know your source of this information? I would like to add to the answer if it is correct. – Nishant Jan 20 '18 at 05:48
  • For example: https://stackoverflow.com/a/47626/5445670 – Solomon Ucko Jan 20 '18 at 15:21
21

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();
Ibungo
  • 1,137
  • 12
  • 23
danjonila
  • 305
  • 2
  • 7
1

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();
}
Jegan
  • 129
  • 3
  • 25
    (1) Doesn't work with negatives [are you a C developer who loves unsigned int?] (2) Relies on truncation [we all know what assume means ...] (3) overly verbose (4) WHY?! – ingyhere Nov 16 '13 at 13:23
  • 1
    Apart from problems described by @ingyhere , it also doesn't work for leading zeroes. 0123 as input becomes 83 – Martin Jul 10 '20 at 10:32
  • 1
    There is absolutely no reason to do any of this. You're attempting to shave off each digit from the integer *backwards*, convert each digit to a character manually, append each digit *one at a time* to the string builder, before reversing the whole thing to get the original ordering back. **Why?** A `StringBuilder` can just **accept the whole integer in one call to append!** And it works across all the special cases your code fails for. You can replace this entire thing with `StringBuilder sb = new StringBuilder(); sb.append(intValue); return sb.toString();` – user229044 May 19 '22 at 17:35