HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

How to convert a char array back to a string?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arrayhowconvertcharstringback

Problem

I have a char array:

char[] a = {'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'};


My current solution is to do

String b = new String(a);


But surely there is a better way of doing this?

Solution

No, that solution is absolutely correct and very minimal.

Note however, that this is a very unusual situation: Because String is handled specially in Java, even "foo" is actually a String. So the need for splitting a String into individual chars and join them back is not required in normal code.

Compare this to C/C++ where "foo" you have a bundle of chars terminated by a zero byte on one side and string on the other side and many conversions between them due do legacy methods.

Context

Stack Overflow Q#7655127, score: 237

Revisions (0)

No revisions yet.