- How to convert an array to a string in Java
- You might also like.
- Java String Array to String
- Java String Array to String
- Java String Array to String Example
- Java Array to String Example
- Convert string array to string in java
- How convert an array of Strings in a single String in java?
- Example
- Output
- Using the StringJoiner class
- Example
- Output
How to convert an array to a string in Java
Sometimes you want to convert an array of strings or integers into a single string. However, unfortunately, there is no direct way to perform this conversion in Java.
The default implementation of the toString() method on an array only tells us about the object’s type and hash code and returns something like [Ljava.lang.String;@f6f4d33 as output.
In this article, we shall look at different ways to convert an array into a string in Java.
The String.join() method returns a new string composed of a set of elements joined together using the specified delimiter:
String[] fruits = "Apple", "Orange", "Mango", "Banana">; String str = String.join(", ", fruits); System.out.println(str); // Apple, Orange, Mango, Banana
You can also pass the strings that you want to join directly to the String.join() method, as shown below:
String str = String.join(" ", "Java", "is", "awesome", "🌟"); System.out.println(str); // Java is awesome 🌟
ListString> animals = List.of("Fox", "Dog", "Loin", "Cow"); String str = String.join("-", animals); System.out.println(str); // Fox-Dog-Loin-Cow CharSequence[] vowels = "a", "e", "i", "o", "u">; String str2 = String.join(",", vowels); System.out.println(str2); // a,e,i,o,u
Java Streams API provides the Collectors.joining() method to join strings from the Stream using a delimiter:
String[] fruits = "Apple", "Orange", "Mango", "Banana">; String str = Arrays.stream(fruits).collect(Collectors.joining(", ")); System.out.println(str); // Apple, Orange, Mango, Banana
Besides delimiter, you can also pass prefix and suffix of your choice to the Collectors.joining() method:
String[] fruits = "Apple", "Orange", "Mango", "Banana">; String str = Arrays.stream(fruits) .collect(Collectors.joining(", ", "[", "]")); System.out.println(str); // [Apple, Orange, Mango, Banana]
The Arrays.toString() method returns a string representation of the contents of the specified array. All array’s elements are joined together using a comma ( , ) as a delimiter and enclosed in square brackets ( [] ) as shown below:
String[] fruits = "Apple", "Orange", "Mango", "Banana">; String str = Arrays.toString(fruits); System.out.println(str); // [Apple, Orange, Mango, Banana]
The best thing about Arrays.toString() is that it accepts both primitive and object arrays and converts them into a string:
int[] number = 1, 2, 3, 4>; System.out.println(Arrays.toString(number)); // [1, 2, 3, 4] double[] prices = 3.46, 9.89, 4.0, 2.89>; System.out.println(Arrays.toString(prices)); // [3.46, 9.89, 4.0, 2.89]
The StringBuilder class is used to create mutable strings in Java. It provides an append() method to append the specified string to the sequence. The toString() method of the StringBuilder class returns a string representation of the data appended. To convert an array to a string using StringBuilder , we have to use a loop to iterate over all array’s elements and then call the append() method to append them into the sequence:
String[] fruits = "Apple", "Orange", "Mango", "Banana">; StringBuilder builder = new StringBuilder(); for (int i = 0; i fruits.length; i++) builder.append(fruits[i]).append(" "); > String str = builder.toString(); System.out.println(str); // Apple Orange Mango Banana
int[] number = 1, 2, 3, 4>; StringBuilder builder = new StringBuilder(); for (int i = 0; i number.length; i++) builder.append(number[i]).append(" "); > String str = builder.toString(); System.out.println(str); // 1 2 3 4
The StringJoiner class was introduced in Java 8, and it provides methods for combining multiple strings into a single string using the specified delimiter:
String path = new StringJoiner("/") .add("/usr") .add("share") .add("projects") .add("java11") .add("examples").toString(); System.out.println(path); // /usr/share/projects/java11/examples
As you can see above, the StringJoiner class provides a very fluent way of joining strings. We can easily chain multiple calls together to build a string.
Finally, the last way to convert an array of strings into a single string is the Apache Commons Lang library. The join() method of the StringUtils class from Commons Lang transforms an array of strings into a single string:
String[] names = "Atta", "Arif", "Meero", "Alex">; String str = StringUtils.join(names, "|"); System.out.println(str); // Atta|Arif|Meero|Alex
To convert a string back into an array in Java, read this article. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
Java String Array to String
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Today we will look into how to convert Java String array to String. Sometimes we have to convert String array to String for specific requirements. For example; we want to log the array contents or we need to convert values of the String array to String and invoke other methods.
Java String Array to String
Most of the time we invoke toString() method of an Object to get the String representation. Let’s see what happens when we invoke toString() method on String array in java.
package com.journaldev.util; public class JavaStringArrayToString < public static void main(String[] args) < String[] strArr = new String[] ; String str = strArr.toString(); System.out.println("Java String array to String = "+str); > >
Below image shows the output produced by the above program. The reason for the above output is because toString() call on the array is going to Object superclass where it’s implemented as below.
Java String Array to String Example
So how to convert String array to String in java. We can use Arrays.toString method that invoke the toString() method on individual elements and use StringBuilder to create String.
public static String toString(Object[] a) < if (a == null) return "null"; int iMax = a.length - 1; if (iMax == -1) return "[]"; StringBuilder b = new StringBuilder(); b.append('['); for (int i = 0; ; i++) < b.append(String.valueOf(a[i])); if (i == iMax) return b.append(']').toString(); b.append(", "); >>
We can also create our own method to convert String array to String if we have some specific format requirements. Below is a simple program showing these methods in action and output produced.
package com.journaldev.util; import java.util.Arrays; public class JavaStringArrayToString < public static void main(String[] args) < String[] strArr = new String[] < "1", "2", "3" >; String str = Arrays.toString(strArr); System.out.println("Java String array to String = " + str); str = convertStringArrayToString(strArr, ","); System.out.println("Convert Java String array to String = " + str); > private static String convertStringArrayToString(String[] strArr, String delimiter) < StringBuilder sb = new StringBuilder(); for (String str : strArr) sb.append(str).append(delimiter); return sb.substring(0, sb.length() - 1); >>
So if we use array toString() method, it returns useless data. Java Arrays class provide toString(Object[] objArr) that iterates over the elements of the array and use their toString() implementation to return the String representation of the array. That’s why when we use this function, we can see that it’s printing the array contents and it can be used for logging purposes. If you want to combine all the String elements in the String array with some specific delimiter, then you can use convertStringArrayToString(String[] strArr, String delimiter) method that returns the String after combining them.
Java Array to String Example
Now let’s extend our String array to String example to use with any other custom classes, here is the implementation.
package com.journaldev.util; import java.util.Arrays; public class JavaArrayToString < public static void main(String[] args) < A[] arr = < new A("1"), new A("2"), new A("3") >; // default toString() method System.out.println(arr.toString()); // using Arrays.toString() for printing object array contents System.out.println(Arrays.toString(arr)); // converting Object Array to String System.out.println(convertObjectArrayToString(arr, ",")); > private static String convertObjectArrayToString(Object[] arr, String delimiter) < StringBuilder sb = new StringBuilder(); for (Object obj : arr) sb.append(obj.toString()).append(delimiter); return sb.substring(0, sb.length() - 1); >> class A < private String name; public A(String name) < this.name = name; >@Override public String toString() < System.out.println("A toString() method called!!"); return this.name; >>
[Lcom.journaldev.util.A;@7852e922 A toString() method called!! A toString() method called!! A toString() method called!! [1, 2, 3] A toString() method called!! A toString() method called!! A toString() method called!! 1,2,3
So we looked at how to convert Java String array to String and then extended it to use with custom objects. That’s all for converting java array to String. You can checkout more core java examples from our GitHub Repository. Reference: Java Arrays toString API Doc
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us
Convert string array to string in java
1. String.join()
Java string class has a join() method, which accepts two arguments
a) A separator
b) An array of CharSequence interface
and returns a string with elements of array combined with the separator. Since string implements CharSequence , it can be supplied to join() . Example,
String[] arr = < "Abc", "Def", "Ghi", "Jkl" >; String joined = String.join("", arr));
This example joins string array elements without any separator. If you want, you can supply a separator as the first argument. join() internally loops over the array and uses Java 8 StringJoiner class(discussed next) to convert array to string.
2. Using StringJoiner
Java 8 StringJoiner is used for joining string values using its add() method.
To convert a string array to string, it can be utilized as below
String[] arr = < "Abc", "Def", "Ghi", "Jkl">; StringJoiner joiner = new StringJoiner(""); for (String string : arr) < joiner.add(string); >System.out.println(joiner);
Constructor of StringJoiner accepts a string, which acts as a delimiter pr separator between joined strings.
So, if you want to join strings with comma as a separator, then provide it as constructor argument.
3. Java streams
Java 8 streams can be used to convert a string array to string as shown below
String[] arr = ; String join = Arrays. stream(arr). collect(Collectors.joining());
- To get the stream over array elements, stream() method is used.
- collect() method is a terminal operation used to combine stream elements, with the help of a collector.
- To get the collector, Collectors.joining() method is used.
joining() joins the stream elements in to a string and returns a collector object.
This method will concatenate any null elements to the resultant string.
To avoid null elements, use stream filter() method as shown below.
Arrays. stream(arr). filter(s -> s != null). collect(Collectors.joining());
String[] arr = ; String join = Joiner.on("").join(arr); System.out.print(join);
If there is a null string in the array, then this method will raise a NullPointerException .
To avoid this, add a skipNulls() method before join() , so that it will ignore any null elements.
String[] arr = ; String join = Joiner.on("").skipNulls().join(arr);
Add below dependency for this library
// MAVEN// GRADLE implementation 'com.google.guava:guava:31.1-jre' com.google.guava guava 31.1-jre
5. Apache Commons Lang
String join = StringUtils.join(arr); System.out.println(join);
join() automatically converts null to an empty string.
Following dependency needs to be added for this library
// MAVEN// GRADLE implementation 'org.apache.commons:commons-lang3:3.12.0' org.apache.commons commons-lang3 3.12.0
6. Using StringBuffer
Iterate over the array with a for loop and add elements to a StringBuffer with its append() method as shown below
StringBuffer buffer = new StringBuffer(); for (String string : arr)
How convert an array of Strings in a single String in java?
The toString() method of the Arrays class accepts a String array (in fact any array) and returns it as a String. Pass your String array to this method as a parameter.
Example
import java.util.Arrays; public class ArrayOfStrings < public static void main(String args[]) < String stringArray[] = ; StringBuffer sb = new StringBuffer(); for(int i = 0; i < stringArray.length; i++) < sb.append(stringArray[i]); >String str = Arrays.toString(stringArray); System.out.println(str); > >
Output
Hello how are you welcome to Tutorialspoint
Using the StringJoiner class
Since Java8 StringJoiner class is introduced this you can construct a sequence of characters separated by desired delimiter.
The add() method accepts a CharacterSequence object (Segment, String, StringBuffer, StringBuilder) and adds it to the current Joiner separating the next and previous elements (if any) with delimiter at the time of constructing it.
The toString() method returns the contents of the current StringJoiner as a Sting object.
Therefore, to convert String array to a single Sting using this class −
- Create an object of StringJoiner.
- Traverse through the Sting array using a loop.
- In the loop add each element of the Sting array to the StringJoiner object.
- Convert the it to String using the toSting() method.
Example
import java.util.StringJoiner; public class ArrayOfStrings < public static void main(String args[]) < String stringArray[] = ; StringJoiner joiner = new StringJoiner(""); for(int i = 0; i < stringArray.length; i++) < joiner.add(stringArray[i]); >String str = joiner.toString(); System.out.println(str); > >
Output
Hello how are you welcome to Tutorialspoint