Convert character array to a String in Java

In this post, we will see how to convert character array to a String using plain Java.

 

1. String constructor

String class contains several overloaded versions of its constructor. One such constructor is String(char[]) that accepts a character array as a parameter. It allocates a new String that represents the sequence of characters contained in the character array argument.

 

Download   Run Code

Output:

Java

 

2. String.valueOf()

Java SE String class provides static valueOf(char[]) method that returns the string representation of the character array argument.

 

Download   Run Code

Output:

Java

 

3. String.copyValueOf()

String class also has copyValueOf(char[]) that is equivalent to valueOf(char[]) which is discussed in last section. It returns a String that contains the characters of specified character array.

 

Download   Run Code

Output:

Java

 

4. Java 8

In Java 8, we can do something like by using Streams.

 

Download   Run Code

Output:

Java

 
Please note that in all approaches discussed above, the contents of the character array are copied. That means that any subsequent modification of the character array will not affect the returned string.

 
Related Post: Convert a String to Character array in Java

 
References: String JavaDoc (Java Platform SE 8)

 
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