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;
// ...
Str
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:
String s = c1 + "" + c2;
That way there's no possibility, however remote, of someone considering whether c1 and c2 will be added together before the concatenation.
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
"" + c1 + c2
is equivalent to
new StringBuffer().append(new Character(c1).toString())
.append(new Character(c2).toString()).toString()
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.
Unless your app needs every ounce of performance, write the code that's quicker to write and easier to read. "" + is a slower-to-execute syntax, but it certainly seems easier to read every time I've used it.