How to Convert Char Array to String in Java

In this section, we will learn how to convert char Array to String in Java.

There are four ways to convert char array to string in Java:

  • Using String class Constructor
  • Using valueOf() Method
  • Using copyValueOf() Method
  • Using StringBuilder Class

Using String Class Constructor

The String class provides a constructor that parses a char[] array as a parameter and allocates a new String. It represents the sequence of the characters (string). If we do any modification in the char[] array, the newly created string remains the same.

Syntax:

Where char[] is an initial value of the string.

In the following example, we have created a character array named ch. After that, we have created a constructor of the String class that parses the char[] array ch as a parameter. It converts the char[] array to the string.

CharArrayToStringExample1.java

Output:

welcome to Javatpoint

Using valueOf() Method

The valueOf() method is a static method of the String class that is also used to convert char[] array to string. The method parses a char[] array as a parameter. It returns a newly allocated string that represents the same sequence of characters contained in the character array. If we do any modification in the char[] array, the newly created string remains the same.

Syntax:

In the following example, we have created a char[] array named chars. After that, we have invoked the valueOf() method of the String class and parses a char[] chars into it. It returns the sequence of characters that we have passed in the parameter.

CharArrayToStringExample2.java

Output:

Tom Cruise

Using copyValueOf() Method

It is similar to the valueOf() method. The copyValueOf() method is also a static method of the String class. It also parses a char[] array. It returns a character sequence (String) that we passed in the parameter.

Syntax:

Where data is the character array.

CharArrayToStringExample3.java

Output:

Good Morning

Using StringBuilder Class

append() Method

The append() method of the StringBuilder class appends the string representation of the char[] array. It parses parameter str that is to be appended. It returns a reference to this object. The working of this method is the same as the method String.valueOf(char[]), and the characters of that string appended to this character sequence.

Syntax:

toString() Method

The toString() method of the StringBuilder class returns a string that represents the data in the sequence. It allocates a new String object and initialized to contain the character sequence. If we do any change in the char[] array, it does not affect the newly created string.

Syntax:

In the following example, we have used append() and toString() method of the StringBuilder class to convert the char[] array to string.

CharArrayToStringExample4.java

Output:

Information Technology

Next TopicJava Tutorial