I always use String.valueOf(integer)
to convert an integer to a string, but I saw someone to do it by integer + ""
. For example,
int i = 0;
String i0 = i + "";
So, is that a good way to convert integer to string?
Though it works, i + ""
is kind of hack to convert int
to String. The + operator on string never designed to use that way. Always use String.valueOf()
Use whatever method is more readable. String.valueOf(i)
or Integer.toString(i)
make your intent much clearer than i + ""
.
It's not only the optimization. I don't like
"" + i
because it does not express what I really want to do.
I don't want to append an integer to an (empty) string. I want to convert an integer to string:
Integer.toString(i)
Or, not my prefered, but still better than concatenation, get a string representation of an object (integer
String.valueOf(i)
N.B: For code that is called very often, like in loops, optimization sure is also a point for not using concatenation.
The thing there is that if you have an Integer i
(non-primitive) and use i + ""
, you may end up with a non-null string of "null"
value if i
is null, while String.valueOf(...)
will throw NullPointerException
in this case.
In all other cases it's the same (also very similar as for the internal process that will be invoked to return the result). Given what's above, it all depends on the context that you use it for, e.x. if you plan to convert the string back to int
/Integer
the +
case, may be more problematic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With