Languages
[Edit]
EN

Java - convert char array to string

7 points
Created by:
Violet-Hoffman
652

In this post we can find couple of different ways how to convert char array to String in java.

Short solutions:

char[] charArr = {'a', 'b', 'c'};

// solution 1
String str1 = new String(charArr); // abc

// solution 2
String str2 = String.valueOf(charArr); // abc

// solution 3
String str3 = String.copyValueOf(charArr); // abc

1. Using String constructor

public class Example1 {

    public static void main(String[] args) {

        char[] charArr = {'a', 'b', 'c'};

        String string = new String(charArr);
        System.out.println(string); // abc
    }
}

Output:

abc

2. Using String.valueOf() or String.copyValueOf()

public class Example2 {

    public static void main(String[] args) {

        char[] charArr = {'a', 'b', 'c'};

        String string1 = String.valueOf(charArr);

        String string2 = String.copyValueOf(charArr);

        System.out.println(string1); // abc
        System.out.println(string2); // abc
    }
}

Output:

abc
abc

3. Using StringBuilder

public class Example3 {

    public static void main(String[] args) {

        char[] charArr = {'a', 'b', 'c'};

        StringBuilder builder = new StringBuilder();
        for (char c : charArr) {
            builder.append(c);
        }

        String string = builder.toString();
        System.out.println(string); // abc
    }
}

Output:

abc

4. Using Java 8 Streams

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Example4 {

    public static void main(String[] args) {

        char[] charArr = {'a', 'b', 'c'};

        Stream<Character> charStream = new String(charArr)
                .chars().mapToObj(c -> (char) c);

        String string = charStream.map(String::valueOf)
                .collect(Collectors.joining());

        System.out.println(string); // abc
    }
}

Output:

abc

5. Using Guava Joiner

import com.google.common.base.Joiner;

public class Example5 {

    public static void main(String[] args) {

        char[] charArr = {'a', 'b', 'c'};

        Character[] charArrBoxed = new String(charArr).chars()
                .mapToObj(c -> (char) c)
                .toArray(Character[]::new);

        String string = Joiner.on("").join(charArrBoxed);

        System.out.println(string); // abc
    }
}

Output:

abc

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - Arrays (popular problems)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join