579

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

1

6 Answers 6

1094

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)
Sign up to request clarification or add additional context in comments.

16 Comments

@Trufa - I would use valueOf() out of these 3.
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 Your last comment is BACKWARDS. Actually, the first way invokes the last. (See String source in JDK at grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/… .)
int oopsPitfall = 0700; String.valueOf(oopsPitfall);
@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.
|
69

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.

Comments

57

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();

3 Comments

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.
It can. Java 11 compiler produces an invocation of makeConcatWithConstants. Some older releases used StringBuffer maybe.
0.) it is shorter to type ! 1.) Is the overhead really significant in real world usage? 2.) why doesn't the compiler optimize it "correctly" (as in: create the most efficient code)?
49

This will do. Pretty trustworthy. : )

    ""+number;

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

5 Comments

@SolomonUcko may I know your source of this information? I would like to add to the answer if it is correct.
@SolomonUcko that's a case for variables. Concat with a constant can be optimized AOT. Unless you have a proof for const-related concat, the link you provided is not relevant.
@user213769 Hmm, that's a good point; I didn't consider that. However, I've tested it now, and it looks like OpenJDK versions 6–8 do in fact do what I described earlier: javap.yawk.at/#rsOEIY However, later versions use java.lang.invoke.StringConcatFactory::makeConcatWithConstants, and since version 19, they use it along with String.valueOf for some reason. IDK why they don't just use String.valueOf by itself...
@SolomonUcko my point exactly, though maybe I should say "no longer relevant" instead of "not relevant" (Java 9 & StringConcatFactory were still really new things in 2018). As to the implementation: I don't have the foggiest, seems like a missed optimization opportunity for me (it's related to array-to-string I think here - a non-array version is slightly different there), but at least a 0-alloc one. Anyway, javac is not an optimizing compiler TBH, so I guess it's up to HotSpot to figure out that it's actually just the var itself.
24

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();

2 Comments

which differences: Integer.toString(i) vs String.valueOf(i) ?
Just checked the android code, String.valueOf(i) is calling the other internally, so might just call the other instead.
2

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();
}

4 Comments

(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?!
Apart from problems described by @ingyhere , it also doesn't work for leading zeroes. 0123 as input becomes 83
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();
@Martin That's not a problem with this code; rather, that's because Java interprets the leading zero as a signal that you're writing the number in octal instead of decimal: docs.oracle.com/javase/specs/jls/se6/html/lexical.html#3.10.1 1 * 8^2 + 2 * 8 + 3 = 8 * 10 + 3

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.