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

There are several ways to convert a char array to a String in Java, which is the process of joining the individual characters in the array into a string sequence. Since the string is immutable in Java, the subsequent modification of the character array does not affect the allocated string. Some of the possible methods are:

1. Using String Constructor

The simplest solution is to pass the char array into the String() constructor. It takes a char array as a parameter and creates a new String object that represents the sequence of characters in the array. It internally uses Arrays.copyOf() to copy the contents of the character array.

Download  Run Code

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

We can encapsulate the string constructor call by using the String.valueOf() method, which internally does the same thing. The String.valueOf() method is a static method that takes a char array as a parameter and returns a new String object that contains the same characters as the array. We can also use the static method String.copyValueOf() that is similar to the String.valueOf() method.

Download  Run Code

3. Using StringBuilder class

Another plausible way of converting a char array to string is using the StringBuilder class. This is a mutable class that can be used to append characters to a string. We can iterate through the char array and append each character to a StringBuilder object. Then, we can use the toString() method of the StringBuilder class to get the final string.

Download  Run Code

4. Using Arrays.toString() method (Not recommended)

The idea here is to get the 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 single space ", ". We can easily get rid of the square brackets by calling the substring() method, and comma and space by using the replaceAll() method.

Download  Run Code

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