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.
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[] {"1","2","3"};
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.
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
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.
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;
}
}
Output produced by the above java array to String example program is;
[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.
Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev
One problem in this conversion it does not add space between the words
- kirtiwardhan
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.