How to Convert Array to String in Java
In this quick tutorial, we’re going to look at different ways to convert an 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 programming needs.
For example, sometimes, we may want to join multiple strings separated by a comma to create a CSV String.
Feel free to check our article on how to convert a string into an array to learn how to do the opposite.
Converting Array to String in Java
Basically, converting an array of elements to a string is very easy and can be done using multiple strategies and methods. However, unfortunately, there is no direct way to achieve that in Java.
Now you may be wondering, why we can’t just use the 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 as output.
Not cool right? It’s not even a human-understandable result.
Using String.join() Method
join() belongs to String class and it can be used to join string array to produce one single String instance.
This method 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 the join() method to create a new string object from 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 turn an Array into a String.
It simply returns the string representation of the specified array. All array’s elements will be separated by “,” and enclosed in square brackets “[]“.
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]
Using StringBuilder append() Method
StringBuilder class can be used to create mutable string objects. It offers the append(String str) method to append a given string to the sequence.
StringBuilder.toString() returns the string representation of the data encapsulated in the StringBuilder object.
In order to use StringBuilder to convert an array to string in Java, we need to follow the following steps:
Create your array - of strings for example
Create a StringBuilder object
Iterate over the array
Use append() method to append every element - string - of the array
Use toString() method to return a string instance from the 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
Using StringJoiner class
StringJoiner is a new class introduced in Java 8, it belongs to the java.util package. It provides methods for joining multiple Strings into one single string object using a specified delimiter.
StringJoiner offers a fluent way to join strings, we can chain the calls and write code in one line.
For example, we can use it 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
The joining() method is defined in Collectors class, it is mainly used to convert multiple strings to a string object.
We can use a delimiter - prefix and suffix too - of our choice to concatenate the input elements in order to construct the string instance.
In general, Collectors class provides 3 overloaded static methods to perform string joining operations.
Let’s see with an example how we can use Collectors.joining() to concatenate multiple strings to form one string:
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]
Using StringUtils (Apache Commons)
StringUtils class from Apache Commons Lang library, offers multiple handy methods for handling string related operations.
It provides multiple join() methods that we can use to convert an array of strings to a single string in Java.
In order to use this class, we will need to add commons-lang3 dependency to our 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 from an array using StringUtils.join():
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
Using Guava Joiner Class
Joiner (a class provided by Guava library) provides clean and concise syntax to handle string concatenation. It takes multiple strings and concatenates them together using delimiters.
Like the Splitter class, Joiner comes with interesting built-in utility methods such as skipNulls which can be used to skip and ignore null values.
To demonstrate this, let’s use the Joiner class to produce a comma separated string from an array:
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 the above methods for some reason or another, we can always create our own implementation.
Here is an example that shows how to define a customized implementation for converting an 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]
How to Convert char Array to String in Java?
There are multiple ways to convert a char array (char[]) to a String in Java. Below, are the list of methods for converting char[] array to a string object.
Using String Constructor
String class provides an overloaded constructor that accepts a char array as an argument. Using a constructor is the most logical and easiest way to create a string from a char array.
All we need to do is passing the array as a parameter to the String constructor and we 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 a new string from a char[] array.
It provides the append() method which can be used to construct a single string from every character of the array.
The conversion logic is very simple:
Create a new StringBuilder instance.
Iterate over the array of characters.
Use append() method to add every character.
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());
}
}
Using Arrays.stream()
Java 8 provides another pretty good solution to create a new string from a character array. We can use Arrays.stream() method to create a stream over an array of characters.
Then, we can use the joining() method of the Collectors class to create the String.
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);
}
}
Using valueOf(char[] data) and copyValueOf(char[] data)
The valueOf() method returns the string representation of the passed argument.
The String class has an overloaded static method: String.valueOf(char [] chars), which takes a char[] as an argument and returns a new string containing all the characters of the passed array.
copyValueOf(char[] data) method serves the same purpose as valueOf(). The two methods are equivalent according to javadocs.
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 possible ways to convert an array to a String in Java.
Happy Learning! If you have any questions, please leave a note in the comments section.