Java - How to convert Char array to String

How to convert Char array to String.

  1. String constructor
  2. String.valueOf()
  3. StringBuilder
  4. Stream

String constructor

Just create a String by passing a char array as an argument to the String constructor.

public void charArrayToString1() {
    char[] charArray = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
    String str = new String(charArray);
    System.out.println(str);
}

result

HelloWorld

String.valueOf()

If you pass a char array as an argument to String.valueOf(), it creates a String.

public void charArrayToString2() {
    char[] charArray = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
    String str = String.valueOf(charArray);
    System.out.println(str);
}

result

HelloWorld

StringBuilder

You can also use StringBuilder.

public void charArrayToString3() {
    char[] charArray = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
    StringBuilder sb = new StringBuilder();
    for (char ch : charArray) {
        sb.append(ch);
    }
    String str = sb.toString();
    System.out.println(str);
}

result

HelloWorld

Stream

You can convert char to String with Stream, and combine Strings to make one String.

Character[] charArray = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
Stream<Character> charStream = Arrays.stream(charArray);
String str = charStream.map(String::valueOf).collect(Collectors.joining());
System.out.println(str);

result

HelloWorld
codechachaCopyright ©2019 codechacha