How to concatenate characters in java?
Do you want to make a string out of them?
String s = new StringBuilder().append(char1).append(char2).append(char3).toString();
Note that
String b = "b";
String s = "a" + b + "c";
Actually compiles to
String s = new StringBuilder("a").append(b).append("c").toString();
Edit: as litb pointed out, you can also do this:
"" + char1 + char2 + char3;
That compiles to the following:
new StringBuilder().append("").append(c).append(c1).append(c2).toString();
Edit (2): Corrected string append comparison since, as cletus points out, a series of strings is handled by the compiler.
The purpose of the above is to illustrate what the compiler does, not to tell you what you should do.
I wasn't going to answer this question but there are two answers here (that are getting voted up!) that are just plain wrong. Consider these expressions:
String a = "a" + "b" + "c";
String b = System.getProperty("blah") + "b";
The first is evaluated at compile-time. The second is evaluated at run-time.
So never replace constant concatenations (of any type) with StringBuilder, StringBuffer or the like. Only use those where variables are invovled and generally only when you're appending a lot of operands or you're appending in a loop.
If the characters are constant, this is fine:
String s = "" + 'a' + 'b' + 'c';
If however they aren't, consider this:
String concat(char... chars) {
if (chars.length == 0) {
return "";
}
StringBuilder s = new StringBuilder(chars.length);
for (char c : chars) {
s.append(c);
}
return s.toString();
}
as an appropriate solution.
However some might be tempted to optimise:
String s = "Name: '" + name + "'"; // String name;
into this:
String s = new StringBuilder().append("Name: ").append(name).append("'").toString();
While this is well-intentioned, the bottom line is DON'T.
Why? As another answer correctly pointed out: the compiler does this for you. So in doing it yourself, you're not allowing the compiler to optimise the code or not depending if its a good idea, the code is harder to read and its unnecessarily complicated.
For low-level optimisation the compiler is better at optimising code than you are.
Let the compiler do its job. In this case the worst case scenario is that the compiler implicitly changes your code to exactly what you wrote. Concatenating 2-3 Strings might be more efficient than constructing a StringBuilder so it might be better to leave it as is. The compiler knows whats best in this regard.
If you have a bunch of chars and want to concat them into a string, why not do
System.out.println("" + char1 + char2 + char3);
?