In this post, we will discuss how can we convert a char array to a string in Java?
1 2 | char array[] = {'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'e', 'r'} String str = "programmer" |
Method 1: using String.valueOf()
To convert a character array into a string in Java we can use the valueOf()
method of the String class.
Using toString()
method will not give any compilation but will definitely result in garbage value, so it is recommended to not use it.
1 2 3 4 5 6 7 8 9 10 11 12 | 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
1 | String: programmer |
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.
1 2 3 4 5 6 7 8 9 10 11 12 | 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
1 | String: programmer |
There are some other methods also to convert a char array to a string, for example, using StringBuilder but it is not so efficient in terms of the number of codes.
If you have any doubts or suggestion then please comment below.