Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

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(...)?

like image 887
MicSim Avatar asked Oct 15 '09 14:10

MicSim


2 Answers

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.

like image 68
Jon Skeet Avatar answered Oct 04 '22 14:10

Jon Skeet


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.

like image 22
Kip Avatar answered Oct 04 '22 14:10

Kip