Is conversion to String using ("" + <int value>) bad practice?

Is conversion to String in Java using

"" + <int value>

bad practice? Does it have any drawbacks compared to String.valueOf(...)?

Code example:

int i = 25;
return "" + i;

vs:

int i = 25;
return String.valueOf(i);

Update: (from comment)

And what about Integer.toString(int i) compared to String.valueOf(...)?


Solution 1:

I would always prefer the String.valueOf version: mostly because it shows what you're trying to do. The aim isn't string concatenation - it's conversion to a string, "the string value of i".

The first form may also be inefficient - depending on whether the compiler spots what you're doing. If it doesn't, it may be creating a new StringBuffer or StringBuilder and appending the value, then converting it to a string.

Funnily enough, I have an article about this very topic - written years and years ago; one of the first Java articles on my web site, IIRC.

Solution 2:

There is also Integer.toString(int i), which gives you the option of getting the string as a hex value as well (by passing a second param of 16).

Edit I just checked the source of String class:

public static String valueOf(int i) {
  return Integer.toString(i, 10);
}

And Integer class:

public static String toString(int i, int radix) {
  if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
    radix = 10;

  /* Use the faster version */
  if (radix == 10) {
    return toString(i);
  }
  ...

If you call String.valueOf(i), it calls Integer.toString(i, 10), which then calls Integer.toString(i).

So Integer.toString(i) should be very slighty faster than String.valueOf(i), since you'd be cutting out two function calls. (Although the first function call could be optimized away by the compiler.)

Of course, a readability argument could still be made for String.valueOf(), since it allows you to change the type of the argument (and even handles nulls!), and the performance difference is negligible.

Solution 3:

Definitely use String.valueOf(i).

Although I'm not sure of the optimizations on the compiler side, worst case scenario if you use "" + :

  1. "" creates a new empty string.
  2. "" + creates a StringBuilder (Java 1.5-16)
  3. "" is appended to the StringBuilder, then

In other words, there is a lot of overhead that occurs if you use string addition. This is why it is not recommended to use the + operator on strings in loops. In general, always use Boolean.valueOf, Integer.valueOf, String.valueOf... etc, when possible. You'll save both on memory and on overhead.

Solution 4:

Regardless of any performance considerations I think the first variant is really ugly. IMHO it's a shame that this kind of "dynamic casting" is even possible in Java.

Solution 5:

Yes, it is IMHO a bad practice.

It would require to memory allocations (unless compiler and/or JIT optimize them). What's more, it will make less evident, what this code tries to do.