There are multiple ways to convert a character array (char[]
) to a string in Java. You can use the string constructor, the String.valueOf()
method and Streams API to convert a sequence of characters to a string object.
Convert char[]
to a string using the String
constructor
The easiest way to convert a character array to a string is using the string constructor e.g. new String(char[])
.
The String
class in Java provides an overloaded constructor that accepts a char
array as an argument. Here is an example:
// Declare char array
char[] chars = {'M', 'a', 'n', 'g', 'o'};
// Convert the char array to a string
String str = new String(chars);
System.out.println(str);
// Mango
Convert char[]
to a string using String.valueOf()
The String.valueOf()
method is yet another simple way to convert a char[]
to a string in Java. It returns the string representation of the passed argument, as shown below:
// Declare char array
char[] chars = {'M', 'a', 'n', 'g', 'o'};
// Convert the char array to a string
String str = String.valueOf(chars);
System.out.println(str);
// Mango
Convert char[]
to a string using Arrays.stream()
Java 8 provides the Arrays.stream()
method to create a stream using an array of characters. Then, you can use the Collectors.joining()
method to convert the stream into a string object:
// Declare char array
Character[] chars = {'M', 'a', 'n', 'g', 'o'};
// Convert the char array to a string
String str = Arrays.stream(chars)
.map(String::valueOf)
.collect(Collectors.joining());
System.out.println(str);
// Mango
Read this article if you want to convert a string into a character array in Java.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.