Java String Array to String

Filed Under: Java

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[] {"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.

java string array to string toString method call output

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());
    }

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);
	}
}

convert string array to string in java

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;
	}
}

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

Comments

  1. kirtiwardhan says:

    One problem in this conversion it does not add space between the words

  2. Dheeban Chakravarthy says:

    super ji. very useful for me.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages