Convert Character Array to String in Java

Many times while doing coding in java we need to Convert Character Array to String in Java. There are many ways in which we can do this.

1). Creating a String object by passing an array name to the constructor
2). Using valueOf() method of String class
3). StringBuilder's toString()
4). Using Java 8 Streams

1). Creating a String object by passing an array name to the constructor

The String class has a constructor that accepts a char array as an argument.

String str = new String(ch); System.out.println(str);

2). Using valueOf() method of String class.

We can use the valueOf() method of String class in Java to copy char array to string.

package com.javacodestuffs.core.chars; public class CharArrayToString { public static void main(String args[]) { // Method 1: Using String object char[] ch = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '!' }; String str = new String(ch); System.out.println(str); // Method 2: Using valueOf method String str2 = String.valueOf(ch); System.out.println(str2); } }

3). StringBuilder's toString()

Here we create the StringBuilder object and append each character by iterating the character array, to get the complete String.

package com.javacodestuffs.core.chars; public class UsingStringBuilder { public static void main(String args[]) { char[] chars = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '!' }; StringBuilder sb = new StringBuilder(); for (char ch: chars) { sb.append(ch); } System.out.println("the final String is : " + sb); } } output: the final String is : Hello World!!

4). Using Java 8 Streams

In java 8 we have use Arrays.stream and then apply the valueOf() over each Character element, gives string as output.

package com.javacodestuffs.core.chars; import java.util.*; import java.util.stream.*; public class UsingStringBuilder { public static void main(String args[]) { Character[] chars = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '!' }; Stream < Character > charStream = Arrays.stream(chars); String string = charStream.map(String::valueOf).collect(Collectors.joining()); System.out.println("the final String is : " + string); } } output: the final String is : Hello World!!

In this article, we have seen how to  Convert Character Array to String in Java with examples. All source code in the article can be found in the GitHub repository.