Strings and Arrays are very closely related in Java because String class represents a sequence of characters!

Sometimes, we need to convert an array into string, but unfortunately there is direct way to achieve this in Java!

Now you may be wondering, why we can’t just use toString() method, since arrays are considered objects in Java ?

Well, if you try to invoke toString() on an array, you will get something like [C@15db9742! Not cool right ? It is not even a human understandable result!

In this tutorial, we are going to look at different ways to convert string to array in Java. You can also check how to convert string into array!

Converting array to string in Java

We often need to convert an array or a list of strings into one single string to meet some basic programing needs. For example, sometimes, we want to join multiple strings separated by comma to create a CSV String!

Actually, converting an array of elements to string is very easy in Java and can be done using multiple strategies and methods!

String.join() method

join() belongs to String class and it can be used to join string array to produce single string instance. It returns a new String composed of CharSequence elements joined together with the help of the specified delimiter!

In this example we are going to use join() method to create a new string object from the elements of an array!

    
        public class ArrayToStringJoin {
            public ArrayToStringJoin() { 
            }
            public static void  main(String[] args) {
                // TODO Auto-generated method stub
                String[] data = {"Turn","Array", "Into", "String","In", "Java", "Example"};
                String joinedstr = String.join(" ", data);
                System.out.println(joinedstr);
                CharSequence[] vowels  = {"a", "e", "i", "o", "u"};
                String joinedvowels = String.join(",", vowels);
                System.out.println(joinedvowels);
                List<String> strList = Arrays.asList("dev", "with", "us", "blog");
                String joinedString = String.join(", ", strList);
                System.out.println(joinedString);
            }
        }
        // Output
        Turn Array Into String In Java Example 
        a,e,i,o,u
        dev, with, us, blog
    

Using Arrays.toString()

Arrays.toString() is a built-in method of Arrays utility class and it provides the simplest way to convert an Array to String.

toString() returns a string representation of the specified array! All array’s elements will be seperated by “,” and enclosed in square brackets “[]“!

Arrays.toString() method

Let’s see how we can use Arrays.toString() method to produce a single string from an array of strings!

    
        public class ArrayToStringToString {
            public ArrayToStringToString() { 
            }
            public static void  main(String[] args) {
                // TODO Auto-generated method stub
                String[] data2 = {"Hello","Array", "String", "Conversion", "Example"};
                String joinedstr2 = Arrays.toString(data2);
                System.out.println(joinedstr2);
            }
        }
        // Output
        [Hello, Array, String, Conversion, Example]
    

StringBuilder append() method

StringBuilder class is used to create mutable string objects. It provides append(String str) method to append a given string to the sequence.

StringBuilder.toString() is the built-in method used to return the string representation of the data encapsuled in StringBuilder object.

In order to use StringBuilder to convert an array to string in Java, you need to follow the following steps:

  • Create your array - of strings for example.

  • Create a StringBuilder object.

  • Iterate over your array.

  • Use append() method to append every element - string - of the array.

  • Use toString() method to return a string instance from stringBuilder object.

    
        public class ArrayToStringStringBuilder {
            public ArrayToStringStringBuilder() { 
            }
            public static void  main(String[] args) {
                // TODO Auto-generated method stub
                String[] data3 = {"Use","StringBuilder", "to", "turn", "Array","into","String","object"};
                StringBuilder stringb = new StringBuilder();
                for (int i = 0; i < data3.length; i++) {
                    stringb.append(data3[i]+" ");
                }
                String joinedstr3 = stringb.toString();
                System.out.println(joinedstr3);
            }
        }
        // Output
        Use StringBuilder to turn Array into String object
    

StringJoiner class

StringJoiner is a new class introduced in Java 8, it belongs to java.util package! It provides methods for joining multiple Strings into one single string object using a specified delimiter!

StringJoiner provides a fluent way to join your strings, it allows you to write your code in one line if you want that.

For example, you can use StringJoiner to join multiple strings separated by “/” to create a full path for a directory in Centos!

    
        public class ArrayToStringStringJoiner {
            public ArrayToStringStringJoiner() { 
            }
            public static void  main(String[] args) {
                // TODO Auto-generated method stub
                String[] data4 = {"path", "to", "devwithus.com", "blog"};
                StringJoiner joiner = new StringJoiner("");
                for (int i = 0; i < data4.length; i++) {
                   joiner.add(data4[i]+"/");
                }
                String joinedstr4 = joiner.toString();
                System.out.println("/"+joinedstr4);
                // Join strings using one single line!
                String newstr = new StringJoiner("/").add("home").add("user").add("file").toString();
                System.out.println(newstr);
            }
        }
        // Output
        /path/to/devwithus.com/blog/
        home/user/file
    

Java 8 Stream API joining()

The joining() method is defined in Collectors class, it is mainly used to convert multiple strings or array of string to a single string object.

You can use a delimiter - prefix and suffix too - of your choice to concatenate the input elements in order to construct one single string object!

In general, Collectors class provides 3 overloaded static methods to perform string joining operations.

collectors joining methods

Let’s see with an example how we can use Collectors.joining() methods to concatenate multiple strings to produce one string object!

    
        public class ArrayToStringJava8 {
            public ArrayToStringJava8() { 
            }
            public static void  main(String[] args) {
                // TODO Auto-generated method stub
                List<String> data5 = Arrays.asList("PHP", "Java", "GoLang", "Kotlin", "Perl");
                String joinedstr5 =   data5.stream()
                                           .collect(Collectors.joining(", ","[","]"));
                System.out.println(joinedstr5);
            }
        }
        // Output
        [PHP, Java, GoLang, Kotlin, Perl]
    

Apache Commons StringUtils join() method

StringUtils class from Apache Commons Lang library, has multiple handy methods for handling string related operations! It provides multiple join() methods that we can be use to turn an array of strings to a single string object.

In order to to use this class, you will need to add commons-lang3 dependency to your dependency management tool file (pom.xml in case of Maven):

    
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>latest-version</version>
        </dependency>
    

The following example shows how to create a new string object from an array using StringUtils join() method.

    
        public class ArrayToStringStringUtils {
            public ArrayToStringStringUtils() { 
            }
            public static void  main(String[] args) {
                // TODO Auto-generated method stub
                String[] data6 = { "John", "Karin", "Charles", "Lucas", "Diana" };
                String joinedstr6 = StringUtils.join(data6,"|");
                System.out.println(joinedstr6);
            }
        }
        // Output
        John|Karin|Charles|Lucas|Diana
    

Guava - Joiner class

Joiner (a class provided by Guava library) provides clean and concise syntax to handle string concatenation! It takes multiple strings and concatenate them together with some delimiter!

Like the Splitter class, Joiner has some interesting built-in utility methods like skipNulls which can be used to skip and ignore null values.

To demonstrate this, let’s use Joiner class on string array to produce a comma separated string:

    
        public class ArrayToStringJoiner {
            public ArrayToStringJoiner() { 
            }
            public static void  main(String[] args) {
                // TODO Auto-generated method stub
                List<String> data7 = Arrays.asList("MOSCOW", "PARIS", "LONDON", "MADRID");
                String joinedstr7 = Joiner.on(":").join(data7);
                System.out.println(joinedstr7);
            }
        }
        // Output
        MOSCOW:PARIS:LONDON:MADRID
    

Using Own Implementation

In case you don’t want to use all above methods for some reason or another, you can always create your own implementation. Here is an example that shows how to define a customized implementation for converting array to string in Java.

    
        public class CustomArrayToString {
            public CustomArrayToString() { 
            }
            private static String arrayTostring(String[] strs) {
                String str = "[";
                for (int i = 0; i < strs.length; i++) {
                    if (i > 0) {
                        str = str + ",";
                    }
                    String item = strs[i];
                    str = str + item;
                }
                str = str + "]";
                return str;
            }
            public static void  main(String[] args) {
                // TODO Auto-generated method stub
                String[] arr = { "United states", "Canada", "France", "United Kingdom" };
                String joinedstr8 = ArrayToString.arrayTostring(arr);
                System.out.println(joinedstr8);
            }
        }
        // Output
        [United states,Canada,France,United Kingdom]
    

Complete code of joining array to string!

The following example summarizes all the methods that we have discussed so far! As always, you can also find the complete source code in GitHub!

    
        import java.util.Arrays;
        import java.util.List;
        import java.util.StringJoiner;
        import java.util.stream.Collectors;
        import org.apache.commons.lang3.StringUtils;
        import com.google.common.base.Joiner;
        public class ArrayToString {
            public ArrayToString() {
            }
            private static String arrayTostring(String[] strs) {
              String str = "[";
              for (int i = 0; i < strs.length; i++) {
                    if (i > 0) {
                        str = str + ",";
                    }
                    String item = strs[i];
                    str = str + item;
                }
                str = str + "]";
                return str;
            }
            public static void  main(String[] args) {
                // using  String.join
                String[] data = {"Turn","Array", "Into", "String","In", "Java", "Example"};
                String joinedstr = String.join(" ", data);
                System.out.println(joinedstr);
                CharSequence[] vowels  = {"a", "e", "i", "o", "u"};
                String joinedvowels = String.join(",", vowels);
                System.out.println(joinedvowels);
                List strList = Arrays.asList("dev", "with", "us", "blog");
                String joinedString = String.join(", ", strList);
                System.out.println(joinedString);
                // using Arrays.toString
                String[] data2 = {"Hello","Array", "String", "Conversion", "Example"};
                String joinedstr2 = Arrays.toString(data2);
                System.out.println(joinedstr2);
                //using  StringBuilder
                String[] data3 = {"Use","StringBuilder", "to", "turn", "Array","to","String","object"};
                StringBuilder stringb = new StringBuilder();
                for (int i = 0; i < data3.length; i++) {
                    stringb.append(data3[i]+" ");
                }
                String joinedstr3 = stringb.toString();
                System.out.println(joinedstr3);
                // using StringJoiner
                String[] data4 = {"path", "to", "devwithus.com", "blog"};
                StringJoiner joiner = new StringJoiner("");
                for (int i = 0; i < data4.length; i++) {
                   joiner.add(data4[i]+"/");
                }
                String joinedstr4 = joiner.toString();
                System.out.println("/"+joinedstr4);
                // using Java 8 Stream API
                List data5 = Arrays.asList("PHP", "Java", "GoLang", "Kotlin", "Perl");
                String joinedstr5 =   data5.stream()
                                           .collect(Collectors.joining(", ","[","]"));
                System.out.println(joinedstr5);
                // using StringUtils
                String[] data6 = { "John", "Karin", "Charles", "Lucas", "Diana" };
                String joinedstr6 = StringUtils.join(data6,"|");
                System.out.println(joinedstr6);
                // using Joiner
                List data7 = Arrays.asList("MOSCOW", "PARIS", "LONDON", "MADRID");
                String joinedstr7 = Joiner.on(":").join(data7);
                System.out.println(joinedstr7);
                // using custom implementation
                String[] arr = { "United states", "Canada", "France", "United Kingdom" };
                String joinedstr8 = ArrayToString.arrayTostring(arr);
                System.out.println(joinedstr8);
            }
        }
    

How to convert char array to string in Java?

There are multiple ways to convert a char array (char[]) to String in Java! Below are the list of methods and approaches which can be to turn char array into string.

Using String constructor

String class provides an overloaded constructor that can accept a char array as an argument, so String constructor is the most logical and easiest way to convert a char array into a String.

All you need to do is just pass the char array as parameter to the String constructor and you are done!

    
        public class StringConstructor {
            public StringConstructor() { 
            }
            public static void  main(String[] args) {
                char[] chars = { 'h', 'd', 'k', 'l', 'f', 'p', 'o', 'i' };
                String mystring = new String(chars);
                System.out.println(mystring);
            }
        }
    

Using StringBuilder

StringBuilder is yet another simple way to produce new string from char array! It has append() method which can be used to form a single string from every char of the array!

The logic behind StringBuilder method is very simple:

  • Create a new StringBuilder instance.

  • Iterate over char array.

  • Use append() method to append your array in a StringBuilder StringBuilder object.

  • Use toString() method to get String object.

    
        public class StringBuilderExample {
            public StringBuilderExample() { 
            }
            public static void  main(String[] args) {
                char[] chararray = { 'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r','l','d' };    
                StringBuilder strb = new StringBuilder();
                for (char mychar : chararray) {
                    strb.append(mychar);
                }
                System.out.println(strb.toString());
            }
        }
    

Java 8 Stream API

Java 8 provides another pretty good solution to create a new string from character array! You can use Arrays.stream() method to create a stream over an array of characters, after that you can use joining() method of Collectors class to construct the String instance!

Let’s look at the following example:

    
        public class Java8StreamAPI {
            public Java8StreamAPI() { 
            }
            public static void  main(String[] args) {
                Character[] charArray = { 'd', 'e', 'v', 'w', 'i', 't', 'h', 'u','s','.','c','o','m' };
                Stream<Character> charStream = Arrays.stream(charArray);
                String mystr = charStream.map(String::valueOf).collect(Collectors.joining());
                System.out.println(mystr);
            }
        }
    

String valueOf(char[] data) and copyValueOf(char[] data)

String class provides multiple version of valueOf() method to return the string representation of the passed argument!It has an overloaded static method String.valueOf(char [] chars) method which takes a char[] array as an argument and returns a new string create containing the characters of the char array.

copyValueOf(char[] data) method serves the same purpose as valueOf()! The two methods are equivalent according to javadocs, they are used to convert char array to string in Java!

String copyValueOf() method

    
        public class valueOfAndCopyValueOf {
            public valueOfAndCopyValueOf() { 
            }
            public static void  main(String[] args) {
                char[] charsarray = { 't', 'k', 'z', 'v', 'y', 'b', 'x', 'n' };
                String mystr1 = String.valueOf(charsarray);
                System.out.println(mystr1);
                String mystr2 = String.copyValueOf(charsarray);
                System.out.println(mystr2);
            }
        }
    

Conclusion:

That’s all folks! In this article, we have explored multiple possible strategies to convert array of elements into new String instance.

Happy Learning! If you have any questions, please leave a note in the comments section.