String conversions - the Good, the Okay-I-Suppose, and the Utterly Horrible

A commonly asked question is "How do I convert <foo> into a String?" where foo is usually a variable of one of the primitive types. There are three common answers to this:
  1. (The Good) String.valueOf(foo)
  2. (The Okay-I-Suppose) Integer.toString(foo) (or Float.toString(foo) etc)
  3. (The Utterly Horrible) foo+"" or ""+foo

The Utterly Horrible

The reasons option 3 is utterly horrible may not be immediately clear to some people, which is why I've written this page. Firstly it's inefficient. It's converted into (typically) 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...

The Okay-I-Suppose

Option 2 is actually pretty reasonable - unless you want to change the type of 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...

The Good

Option 1 is great. It works for any type - primitive or reference, even a null reference. It's efficient (depending on the libraries it may be very slightly less efficient than option 2, but basically insignificantly so) and above all, it says what it does in the simplest possible terms. You want the value of foo as a String? String.valueOf(foo); is about as close to you're going to come to totally self-describing code.

Back to the main page.