Concatenate chars to form String in java

Use str = ""+a+b+c;

Here the first + is String concat, so the result will be a String. Note where the "" lies is important.

Or (maybe) better, use a StringBuilder.


You can use StringBuilder:

    StringBuilder sb = new StringBuilder();
    sb.append('a');
    sb.append('b');
    sb.append('c');
    String str = sb.toString()

Or if you already have the characters, you can pass a character array to the String constructor:

String str = new String(new char[]{'a', 'b', 'c'});

Use StringBuilder:

String str;
Char a, b, c;
a = 'i';
b = 'c';
c = 'e';

StringBuilder sb = new StringBuilder();
sb.append(a);
sb.append(b);
sb.append(c);
str = sb.toString();

One-liner:

new StringBuilder().append(a).append(b).append(c).toString();

Doing ""+a+b+c gives:

new StringBuilder().append("").append(a).append(b).append(c).toString();

I asked some time ago related question.

Tags:

Java