In this article, we will take a look at different ways to convert a char array to string in java with example programs and their explanations.
A char array is an array of characters and is of type char[]
.
java.lang.String class has a constructor which takes a character array as argument and returns a String whose characters are the elements of this char array. Example,
char [] arr = {'c','o','d','i','p','p','a'}; String str = new String(arr); System.out.println("Char array in string is: " + str);
Output of this program is
Char array in string is: codippa
Method 2: Using valueOf() method
String class has a valueOf()
method which takes a char array argument and returns a String with characters as the value of array elements.
valueOf()
is a static method, so we do not need to create an object of String class. Example code is given below.
char [] arr = {'c','o','d','i','p','p','a'}; String str = String.valueOf(arr); System.out.println("Char array in string is: " + str);
Output of this program is
Char array in string is: codippa
Iterate over the char array using a loop. Add each character to a String inside loop so that after the loop completes, the resultant String contains all the characters.
Since, String is immutable, which means every time a character is added, a new String object is created. For large character array, this would consume a lot of memory.
Therefore, instead of adding character to a String, we should use StringBuilder
or StringBuffer
classes.
Example program is given below.
char [] arr = {'c','o','d','i','p','p','a'}; StringBuilder builder = new StringBuilder(); for (char c : arr) { builder.append(c); } String str = builder.toString(); System.out.println("Char array in string is: " + str);
Above example uses enhanced for loop to iterate over the character array, but, simple for
loop can also be used.
Output of this program is
Char array in string is: codippa
Method 4: Using copyValueOf() method
String class has a copyValueOf()
method which takes a char array as argument and returns it as a String.
This method is the same as valueOf()
method and it is also static
. Example,
char [] arr = {'c','o','d','i','p','p','a'}; String str = String.copyValueOf(arr); System.out.println("Char array in string is: " + str);
Output of this code is
Char array in string is: codippa
Do not forget to click the clap if the article was useful.