How to concatenate characters in java?

Wilson picture Wilson · Nov 30, 2008 · Viewed 225.6k times · Source

How do you concatenate characters in java? Concatenating strings would only require a + between the strings, but concatenating chars using + will change the value of the char into ascii and hence giving a numerical output. I want to do System.out.println(char1+char2+char3... and create a String word like this.

I could do

System.out.print(char1);
System.out.print(char2);
System.out.print(char3);

But, this will only get me the characters in 1 line. I need it as a string. Any help would be appreciated.

Thanks

Answer

Dustin picture Dustin · Nov 30, 2008

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.