Convert Character array to string in Java

The most efficient way to do it is most likely this:

Character[] chars = ...

StringBuilder sb = new StringBuilder(chars.length);
for (Character c : chars)
    sb.append(c.charValue());

String str = sb.toString();

Notes:

  1. Using a StringBuilder avoids creating multiple intermediate strings.
  2. Providing the initial size avoids reallocations.
  3. Using charValue() avoids calling Character.toString() ...

However, I'd probably go with @Torious's elegant answer unless performance was a significant issue.


Incidentally, the JLS says that the compiler is permitted to optimize String concatenation expressions using equivalent StringBuilder code ... but it does not sanction that optimization across multiple statements. Therefore something like this:

    String s = ""
    for (Character c : chars) {
        s += c;
    }

is likely to do lots of separate concatenations, creating (and discarding) lots of intermediate strings.


Character[] a = ...
new String(ArrayUtils.toPrimitive(a));

ArrayUtils is part of Apache Commons Lang.


Iterate and concatenate approach:

Character[] chars = {new Character('a'),new Character('b'),new Character('c')};

StringBuilder builder = new StringBuilder();

for (Character c : chars)
    builder.append(c);

System.out.println(builder.toString());

Output:

abc

Tags:

Java

String

Char