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(…)?
I would always prefer the
String.valueOfversion: 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 ofi".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.