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:
c1
and c2
are visually on the same level String.valueOf(c1) + c2
suggests something is special about c1
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);
Concatenating with an Empty String VariableYou can use the concat() method with an empty string variable to concatenate primitive string values. By declaring a variable called totn_string as an empty string or '', you can invoke the String concat() method to concatenate primitive string values together.
The most efficient is to use StringBuilder, like so: StringBuilder sb = new StringBuilder(); sb. Append("string1"); sb.
You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
Using StringBuilder or StringBuffer StringBuilder is a widely used and recommended way to concatenate two strings in Java. It is mutable, unlike string, meaning that we can change the value of the object.
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.
The problem with that construct is that it usually doesn't express the intent.
It represents concatenation of a String with another value, but concatenation is not usually the goal of this line.
In the specific case that you demonstrated, concatenation is actually the goal, so this code does express the intent.
In the more common use of this approach (String s = "" + intValue;
), the concatentation is merely a tolerated side-effect, while the conversion of intValue
is the actual goal. And a simple String.valueOf(intValue)
expresses that intent much clearer.
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