Let's say I have two char
variables, and later on I want to concatenate them into a string. This is how I would do it:
char c1, c2;
// ...
String s = "" + c1 + c2;
I've seen people who say that the "" +
"trick" is "ugly", etc, and that you should use String.valueOf
or Character.toString
instead. I prefer this construct because:
- I prefer using language feature instead of API call if possible
- In general, isn't the language usually more stable than the API?
- If language feature only hides API call, then even stronger reason to prefer it!
- More abstract! Hiding is good!
- I like that the
c1
andc2
are visually on the same levelString.valueOf(c1) + c2
suggests something is special aboutc1
- It's shorter.
Is there really a good argument why String.valueOf
or Character.toString
is preferrable to "" +
?
Trivia: in java.lang.AssertionError
, the following line appears 7 times, each with a different type:
this("" + detailMessage);
Your arguments are good; this is one of the more expressive areas of the Java language, and the
"" +
idiom seems well entrenched, as you discovered.See String concatenation in the JLS. An expression like
is equivalent to
except that all of the intermediate objects are not necessary (so efficiency is not a motive). The spec says that an implementation can use the
StringBuffer
or not. Since this feature is built into the language, I see no reason to use the more verbose form, especially in an already verbose language.The best way to know is to compile / decompile your code, I used Jad http://en.wikipedia.org/wiki/JAD_(JAva_Decompiler) for that, you will see that your expression was converted into
String s = (new StringBuilder()).append("").append(ci).append(c2).toString();
As you can see javac actually included append("") call, but its cost is negligible, noting is appended to internal StringBuilder buffer, you can check StringBuilder's source
I prefer using
String.valueOf
for single conversions - but in your case you really want concatenation.However, I would suggest that this version would remove all potential ambiguity:
That way there's no possibility, however remote, of someone considering whether c1 and c2 will be added together before the concatenation.