Summary: In this programming example, we will learn to convert a char array into a string in Java.
Example:
char array[] = {'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'e', 'r'} String str = "programmer"
Method 1: using String.valueOf()
The String class’s valueOf()
method converts a char array passed as an argument into a string in Java.
import java.util.*;
public class Main
{
public static void main(String[] args) {
char array[] = {'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'e', 'r'};
String str = String.valueOf(array);
System.out.println("String: "+ str);
}
}
Output:
String: programmer
We should not use the toString()
method to convert a char array into a string as it will return the trash value instead.
Method 2: using String Constructor
The String class has an overloaded parametrized constructor that takes a char array as an argument and thus internally converts it to a string.
import java.util.*;
public class Main
{
public static void main(String[] args) {
char array[] = {'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'e', 'r'};
String str = new String(array);
System.out.println("String: "+ str);
}
}
Output:
String: programmer
There are also some other ways to convert a char array to a string, for example, using StringBuilder but it’s not so efficient and comparatively requires more boilerplate code.