foo
> into a
String?" where foo
is usually a variable of one of the primitive
types. There are three common answers to this:
String.valueOf(foo)
Integer.toString(foo)
(or
Float.toString(foo)
etc)
foo+""
or ""+foo
new StringBuffer ().append (foo).append ("").toString()
.
Some compilers may well remove the final call to append, as they
know it's useless. You're still building a StringBuffer up for no
good reason though. Also, depending on the exact implementation, you
may end up with a string which is backed by a character array which
is longer than it needs to be, as a StringBuffer is likely to be
created with a buffer of 16 characters, which is almost always more
than you actually need.
This, however, is not the primary reason to avoid option 3. It probably won't make much difference in the long run, and premature optimisation is the root of all evil, of course. The primary reason is clarity/readability. Some people claim it's the most readable option just because it's shorter. I claim it's the least readable option because it mentions two concepts which are entirely unrelated to what we want to do (ie addition/concatenation and the empty string) but doesn't mention at all what we do want to do (namely find the String value equivalent.) Imagine you were a new Java programmer - which options really demonstrate what you want to do?
Unfortunately, I suspect people will still post sample code on newsgroups which uses this horrible idiom. I'll just refer them here...
foo
. The only thing I have against it is
demonstrated in the way I had to describe it - namely that I had to
give an "(or ... etc)" clause. Really, we just want the value of
foo
as a String, without needing to remember what type
it is. Which leads me onto...
String.valueOf(foo);
is about as close to you're going
to come to totally self-describing code.
Back to the main page.