Table of Contents
A string is defined as a collection of characters. A character array differs from a string in that the string is terminated with the special character “\0.” A string is transformed from a character array and vice versa. We’ll consider converting a character array to a string in this article.
Methods:
- Using copyOf() method of Arrays class
- Using StringBuilder class
- Using valueOf() method of String class
- Using copyValueOf() method of String class
- Using Collectors in Streams
- Using String class Constructor
Let us examine each of the methods in detail and implement them using a clean Java program.
Converting character array to string in Java
Function 1: Using the Array class’s copyOf() method
The String constructor accepts the provided character as an argument. Arrays are used to copy the contents of the character array by default. The Arrays class has a copyOf() function.
Example: A program for Converting Character Array to String in Java
// Using copyOf() method ofArrays class // Main class class CodeunderscoredArrayClass { // Method 1 // To convert a character // array to a string using the constructor public static String toString(char[] a) { // Creating object of String class String string = new String(a); return string; } // Main driver method public static void main(String args[]) { // Character array char s[] = { 'c', 'o', 'd', 'e', 'u', 'n', 'd','e', 'r', 's', 'c', 'o', 'r', 'e', 'd' }; // Printing converted string from character array System.out.println(toString(s)); } }
Method 2: Making use of the StringBuilder class
What if we wanted to make a String out of a collection of char arrays? Then we can create a StringBuilder object and utilize its append(char[]) function to join all of the elements together.
The StringBuilder class is also used to transform a character array into a string. The idea is to cycle through the character array and attach each character to the end of the string because a StringBuilder is a changeable class. Finally, the string contains the characters’ string form. Later, we’ll utilize the toString() method to retrieve its String representation.
The StringBuilder class’s append() method appends the char[] array’s string representation.
It parses the to-be-appended parameter str. This object is returned as a reference. This function works similar to String.valueOf(char[]), except that the characters of that string are appended to this character sequence.
The syntax is as follows:
public StringBuilder append(char[] str)
The toString() method
The StringBuilder class’s toString() method returns a string representing the sequence’s data. It creates a new String object and sets its initial value to the character sequence. Any changes we make to the char[] array do not affect the freshly formed string.
The syntax is as follows:
public String toString()
To convert the char[] array to string in the following example, we utilized the StringBuilder class’s append() and toString() methods.
Example: Program for Converting Character Array to String in Java
// Using StringBuilder class // importing required classes import java.util.*; // Main class public class CodeunderscoredCharacterArray { // Method for con vert a character array to a string // using the StringBuilder class public static String toString(char[] theChar) { // Creating object of String class StringBuilder stringBuilder = new StringBuilder(); // Creating a string using append() method for (int i = 0; i < theChar.length; i++) { stringBuilder.append(theChar[i]); } return stringBuilder.toString(); } // The Main driver method public static void main(String args[]) { // Custom input as character array char charArray[] = { 'c', 'o', 'd', 'e', 'u', 'n', 'd','e', 'r', 's', 'c', 'o', 'r', 'e', 'd' }; // Printing the string // corresponding to character array System.out.println(toString(charArray)); } }
Example: String Builder
@Test public void StringBuilderOK() { final char[][] arrayOfCharArray = { { 'c', 'o' }, { 'd', 'e', 'u', 'n' }, { 'd', 'e', 'r', 's', 'c', 'o', 'e', 'd' } }; StringBuilder stringBuilder = new StringBuilder(); for (char[] subArray : arrayOfCharArray) { stringBuilder.append(subArray); } assertThat(sb.toString(), is("codeunderscored")); }
We may make the following code even more efficient by creating a StringBuilder with the required length.
Example: Char Array to String Using StringBuilder
public class CodeCharArrayToString { public static void main(String[] args) { //character array char[] charVals = {'C', 'o', 'd', 'e', ' ', 'U', 'n', 'd', 'e', 'r', 's', 'c', 'o', 'r', 'e', 'd'}; //creating an object of the StringBuilder class StringBuilder stringBuilder = new StringBuilder(); //Java for-each loop for(char ch: charVals) { // the method appends the representation of the string as a char array stringBuilder.append(ch); } //the toString() method is responsible for returning a string that represents data in the sequence String stringVal = stringBuilder.toString(); //prints the string System.out.println(stringVal); } }
Function 3: Using the String class’s valueOf() method
The valueOf() function of the String class is also used to convert a character array to a string.
This method automatically changes the character array to a format that displays the whole value of the characters in the array. This function converts a string from an int, float, double, char, boolean, or even an object. We’ll accomplish our goal by transforming our character array into a string.
In the following example, we’ve generated a char[] array named charArray. After that, we used the String class’s valueOf() method to parse a char[] charArray into it. The latter returns the character sequence we specified in the parameter.
Example: A program for Converting a Character Array to String in Java
// Using valueOf() method of String class // Main class class CodeunderscoredCharacterArrayToString { // Method 1 // To convert a character array to string // using the valueOf() method public static String toString(char[] theChar) { // Creating an object of String class String strVal = String.valueOf(theChar); return strVal; } // Method 2 // Main driver method public static void main(String args[]) { // Custom input character array char charArray[] = { 'c', 'o', 'd', 'e', 'u', 'n', 'd','e', 'r', 's', 'c', 'o', 'r', 'e', 'd' }; // Print the corresponding string to // character array System.out.println(toString(charArray)); } }
In the subsequent section, we look at another example where the valueOf() method converts a char array to a string.
The first step is creating a character array as follows:
char[] arrVal = { 'c', 'o', 'd', 'e' };
Then the valueOf() method will take over to convert the entire array into a string, as shown below.
String strVal = String.valueOf(arr);
We then put all of these together as a complete function called, CodeunderscoredValueOf() as illustrated below.
public class CodeunderscoredValueOf { public static void main(String []args) { char[] arrVal = { 'c', 'o', 'd', 'e' }; String strVal = String.valueOf(arrVal); System.out.println(strVal); } }
Function 4: Using the String class’s copyValueOf() method
It functions like the valueOf() method. The String class’s copyValueOf() method is also a static method. A char[] array is also parsed. In addition, it returns the character sequence (String) we specified in the parameter.
The character array’s contents are copied and then edited without impacting the string to be returned. This approach also allows us to convert the character array to string, as seen in the following example.
Example: Program for Converting a Character Array to String in Java
// Using copyValueOf() method of String class // Importing String class import java.util.*; // Main class class CodeunderscoredCharacterArrayToString { // Main driver method public static void main(String[] args) { // Customly declaring an input character array char charArray[] = { 'c', 'o', 'd', 'e', 'u', 'n', 'd','e', 'r', 's', 'c', 'o', 'r', 'e', 'd' }; // Using copyValueOf() over string and // storing it in a string String strVal = String.copyValueOf(arr); // Printing the converted string corresponding // character array System.out.print(strVal); } }
Let’s look at another example where the copyValueOf() method is used to convert a char array to a string.
public class CodeunderscoredCopyValueOf { public static void main(String []args) { char[] arrVal = { 'c', 'o', 'd', 'e' }; String strVal = String.copyValueOf(arrVal, 1, 2); System.out.println(strVal); } }
String#copyValueOf is a method that is semantically equivalent to the valueOf() method, but it was only helpful in the early Java releases. The copyValueOf() function is obsolete as of today, and we don’t advocate utilizing it.
Function 5: Using Collectors in Streams in Java
With the advent of streams in java8, we immediately use Collectors in streams to alter our character input array members and then use the joining() method to return a single string, which we then print.
Example: Program for Converting a Character array to String in Java
// Using Collectors in Streams in Java8 // Importing Collectos and Stream classes // from java.util.stream package import java.util.stream.Collectors; import java.util.stream.Stream; // Main class class CodeunderscoredCharacterArrayToString { // Main driver method public static void main(String[] args) { // Custom input character array char[] charVal = { 'c', 'o', 'd', 'e', 'u', 'n', 'd','e', 'r', 's', 'c', 'o', 'r', 'e', 'd' }; // Using collectors array elements collection and // subsequently using the join method to return a single // string String strVal = Stream.of(charVal) .map(arr -> new String(arr)) .collect(Collectors.joining()); // Printing the stream received from Collectors System.out.println(strVal); } }
We can open a stream across an array of type T using the Arrays.stream(T[] object) method. Subsequently, we can use the Collectors.joining() function to create a String with a Character array.
@Test public void StreamCollectors() { final Character[] charArray = { 'c', 'o', 'd', 'e', 'u', 'n', 'd','e', 'r', 's', 'c', 'o', 'r', 'e', 'd' }; Stream<Character> charStream = Arrays.stream(charArray); String stringVal = charStream.map(String::valueOf).collect(Collectors.joining()); assertThat(stringVal, is("codeunderscored")); }
The disadvantage of this technique is that we are executing valueOf() on each Character element, which will be slow.
Example: Using String object and Using valueOf method
This example shows how to convert a char array to a String using both the valueOf() method of String class and creating String object by passing array name to the constructor. We have a char array ch, and we have used the char array to construct two strings, str, and str1.
class CharArrayToString { public static void main(String args[]) { // Method 1: Using String object char[] charVal = {'g', 'o', 'o', 'd', ' ', 'm', 'o', 'r', 'n', 'i', 'n', 'g'}; String strVal = new String(charVal); System.out.println(strVal); // Method 2: Using valueOf method String strTwoVal = String.valueOf(charVal); System.out.println(strTwoVal); } }
Guava Joiner (Common Base)
Let’s pretend the string we’re trying to make is a delimited string. Guava provides us with a useful method:
@Test public void GuavaCommonBaseJoiners() { final Character[] charArray = { 'c', 'o', 'd', 'e', 'u', 'n', 'd','e', 'r', 's', 'c', 'o', 'r', 'e', 'd' }; String stringJoiner = Joiner.on("|").join(charArray); assertThat(stringJoiner, is("c|o|d|e|u|d|e|r|s|c|o|r|e|d")); }
It’s worth noting that the join() method only accepts a Character array, not a raw char array.
Constructing a String Class Constructor
A constructor in the String class takes a char[] array as an argument and allocates a new String. It denotes the order in which the characters appear (string). The freshly formed string remains unchanged if we change the char[] array.
The syntax is as follows:
public String (char[] value)
Where char[] is the string’s starting value, subsequently, we’ve constructed a character array called chVal in the example below. After that, we developed a String constructor that takes the char[] array chVal as a parameter and parsed it. The char[] array is converted to a string.
public class CharArrayToStringConstructor { public static void main(String args[]) { //character array char[] chVal = { 'c', 'o', 'd', 'e', 'u', 'n', 'd','e', 'r', 's', 'c', 'o', 'r', 'e', 'd' }; //String class's constructor that parses char array as a parameter String stringVal = new String(chVal); //prints the string System.out.println(stringVal); } }
Conclusion
This article explored converting a character array to its String representation in Java. To convert a char array to a string in Java, use the valueOf() function. The valueOf() method is a String class static method that you may use to convert a char[] array to a string. The method parses a char[] array as an argument. Then it returns a newly allocated string with the same sequence of characters as the character array. The freshly formed string remains unchanged if we change the char[] array.
In addition, the copyValueOf() method can also be used to represent the character sequence in the array given. It returns a string containing the characters from the character array supplied.
The constructor of the String class is overloaded in various places. String(char[]) is a constructor that takes a character array as an argument. It then creates a new string to reflect the character sequence provided in the character array parameter.