Convert char array to String in Java

In this post, we will discuss how to convert char array to String in Java. A new String should be allocated that represents the sequence of characters contained in the char array. Since String is immutable in Java, the subsequent modification of the character array does not affect the allocated string.

 

1. Using String Constructor

The simplest solution is to pass the char array into the String constructor. The String constructor internally uses Arrays.copyOf() to copy the contents of the character array.

 

Download   Run Code

Output:

Techie Delight

 

2. String.valueOf() or String.copyValueOf()

We can encapsulate the String construtor call by using String.valueOf() or String.copyValueOf() which internally does the same thing.

 

Download   Run Code

Output:

Techie Delight

 

3. Using StringBuilder

Another plausible way of converting a char array to String is using StringBuilder in Java. The idea is to iterate over the characters and append each char to a StringBuilder. Finally, call toString() method on the StringBuilder when iterated over all chars.

 

Download   Run Code

Output:

Techie Delight

 

4. toString() + substring() + Regex

(Not recommended)

The idea here is to get a string representation of the specified array. The string representation consists of a list of the array’s elements, enclosed in square brackets ("[]") and all adjacent elements are separated by a comma followed by a space ", ".

We can easily get rid of the square brackets by calling substring() function, and comma + space by using replaceAll() method.

 

Download   Run Code

Output:

Techie Delight

 

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz