I'm working on a project where all conversions from int
to String
are done like this:
int i = 5;
String strI = "" + i;
I'm not familiar with Java.
Is this usual practice or is something wrong, as I suppose?
javastringtype-conversion
I'm working on a project where all conversions from int
to String
are done like this:
int i = 5;
String strI = "" + i;
I'm not familiar with Java.
Is this usual practice or is something wrong, as I suppose?
Best Answer
Normal ways would be
Integer.toString(i)
orString.valueOf(i)
.The concatenation will work, but it is unconventional and could be a bad smell as it suggests the author doesn't know about the two methods above (what else might they not know?).
Java has special support for the + operator when used with strings (see the documentation) which translates the code you posted into:
at compile-time. It's slightly less efficient (
sb.append()
ends up callingInteger.getChars()
, which is whatInteger.toString()
would've done anyway), but it works.To answer Grodriguez's comment: ** No, the compiler doesn't optimise out the empty string in this case - look:
Initialise the StringBuilder:
Append the empty string:
Append the integer:
Extract the final string:
There's a proposal and ongoing work to change this behaviour, targetted for JDK 9.