Java String Array to String With Examples

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.

Below image shows the output produced by the above program.

java-string-array-to-string

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.

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.

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.

Output produced by the above java array to String example program is;

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.

Reference: Java Arrays toString API Doc

By admin

Leave a Reply