Tutorial

Java String Array to String

Published on August 3, 2022
Default avatar

By Pankaj

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

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
May 5, 2021

=> String.join(“,”,strArr )

- SKU

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    December 25, 2014

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

    - kirtiwardhan

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      December 18, 2014

      super ji. very useful for me.

      - Dheeban Chakravarthy

        Try DigitalOcean for free

        Click below to sign up and get $200 of credit to try our products over 60 days!

        Sign up

        Join the Tech Talk
        Success! Thank you! Please check your email for further details.

        Please complete your information!

        Get our biweekly newsletter

        Sign up for Infrastructure as a Newsletter.

        Hollie's Hub for Good

        Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

        Become a contributor

        Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

        Welcome to the developer cloud

        DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

        Learn more
        DigitalOcean Cloud Control Panel