This post will discuss how to convert a primitive character array to a string in Java.

Converting a character array to a string can be useful for manipulating text data or displaying it to the user. There are several ways to convert a character array to a string in Java:

1. Using String Constructor

The String class contains several overloaded versions of its constructor. One such constructor is String(char[]) that accepts a character array as an argument and allocates a new string representing the same sequence of characters as contained in the character array.

Download  Run Code

2. Using String.valueOf() method

The valueOf() method is a static method of the String class that also takes a character array as a parameter and returns a string that contains the same characters as the character array argument. For example:

Download  Run Code

3. Using String.copyValueOf() method

The copyValueOf() method is similar to the valueOf() method, but it allows specifying the offset and length of the character array to be copied. If copyValueOf() method is called with a single argument, it returns a string that contains all the characters of the specified character array. For example:

Download  Run Code

4. Using Streams API

This uses a functional programming approach that can process elements of a collection in parallel. It converts the character array to a stream of characters and then collects them into a string using the joining collector. For example:

Download  Run Code

5. Using StringBuilder class

Finally, we can use a mutable class that can append characters to a string. We can iterate through the character array and appends each character to the StringBuilder instance. Then, we can use the toString() method of the StringBuilder class to get the final string. For example:

Download  Run Code

That’s all about converting a character array to a String in Java.

 
Related Post:

Convert a String to Character array in Java

 
Reference: String Javadoc SE 21