JavaDevNotes.com

Java Array To String

Java objects have the toString() method to convert the instance to it's String representation. If you will try to invoke the toString() method of an Array, the result will be some weird String like [I@70f9f9d8. This does not seems logical, say for example you wish to write the String to logs. It is more useful to convert a Java Array to a String that gives human understandable results. Below are some examples on how to do that.

Convert Java String Array To String Using java.util.Arrays

The simplest way to convert an Array to String is by using the java.util.Arrays class. It has already a built in method to perform this operation, where the result is human understandable. Here is an example usage:
import java.util.Arrays;
public class Test {
   public static void main(String[] args) {
      String[] testArray = {"Apple", "Banana", "Carrots"};
      String testString = Arrays.toString(testArray);
      System.out.println(testString);
   }
}
First is we need to import the class using import java.util.Arrays; and then we can invoke it's toString method statically. The example above uses a String array with three contents. The output of the code above is shown below:
[Apple, Banana, Carrots]
Notice that the contents of the array are concatenated and separated with comma. The whole String is then enclosed with square brackets. If we use it to convert an empty Array:
String[] testArray = {};
String testString = Arrays.toString(testArray);
System.out.println(testString);
The output will be just the square brackets:
[]

Convert Using Own Implementation

If we do not wish to use the import java.util.Arrays; class, we can always implement our own method. Here is an example code that will have the same output as using the Arrays.toString() method above.
public class Test {
   private static String mytoString(String[] theAray) {
      String result = "[";
      for (int i = 0; i < theAray.length; i++) {
         if (i > 0) {
            result = result + ",";
         }
         String item = theAray[i];
         result = result + item;
      }
      result = result + "]";
      return result;
   }
   public static void main(String[] args) {
      String[] testArray = { "Apple", "Banana", "Carrots" };
      String testString = mytoString(testArray);
      System.out.println(testString);
   }
}

Here is a slightly modified version that uses StringBuilder to make the performance better. I.e. run faster.

public class Test {
   private static String mytoString(String[] theAray) {
      StringBuilder sb = new StringBuilder();
      sb.append("[");
      for (int i = 0; i < theAray.length; i++) {
         if (i > 0) {
            sb.append(",");
         }
         String item = theAray[i];
         sb.append(item);
      }
      sb.append("]");
      return sb.toString();
   }
   public static void main(String[] args) {
      String[] testArray = { "Apple", "Banana", "Carrots" };
      String testString = mytoString(testArray);
      System.out.println(testString);
   }
}

The advantage of using our own implementation is that we can tweak it to suit our requirements.

Convert Java Array To String With Custom Delimiter or Separator

The examples above uses comma as delimiter to convert an Array to String. But sometimes, requirements needs to convert an array to String using custom delimiter or separator. Unfortunately, we can not specify a custom delimiter using the class import java.util.Arrays; . Here, a custom implementation will be handy. Below is an example where the delimiter is passed as a parameter to a custom method:
public class Test {
   private static String mytoString(String[] theAray, String delimiter) {
      StringBuilder sb = new StringBuilder();
      for (int i = 0; i < theAray.length; i++) {
         if (i > 0) {
            sb.append(delimiter);
         }
         String item = theAray[i];
         sb.append(item);
      }
      return sb.toString();
   }
   public static void main(String[] args) {
      String[] testArray = { "Apple", "Banana", "Carrots" };
      System.out.println(mytoString(testArray, ", "));
      System.out.println(mytoString(testArray, " - "));
      System.out.println(mytoString(testArray, " | "));
      System.out.println(mytoString(testArray, " + "));
   }
}
The change is very minimal with the implementation in the previous example. Instead of using hard-coded comma as delimiter, the method now uses the delimiter parameter. The main method invokes the method using different delimiters. The output of the code above is shown below:
Apple, Banana, Carrots
Apple - Banana - Carrots
Apple | Banana | Carrots
Apple + Banana + Carrots

Convert Multidimensional arrays to String

It is more common to deal with one dimensional arrays when we are coding. But occasionally, we work with Multidimensional arrays. If we use the Arrays.toString() on it, the output is different. For example:

String[][] testArray = { { "Apple", "Banana" }, { "Carrots", "Orance" } };
String myString = Arrays.toString(testArray);
System.out.println(myString);
Will render this output:
[[Ljava.lang.String;@2b820dda, [Ljava.lang.String;@675b7986]
To fix this, we can use the Arrays.deepToString() method. This method returns a string representation of the "deep contents" of the given array. What it does is that if elements of an array are array themselves, those will be converted properly also. This method is really designed for use with converting multidimensional arrays to String. Here is the modified code that should work:
String[][] testArray = { { "Apple", "Banana" }, { "Carrots", "Orance" } };
String myString = Arrays.deepToString(testArray);
System.out.println(myString);
And the output will be fixed. This should be the rendered in the console:
[[Apple, Banana], [Carrots, Orance]]

Converting different types of Array

Here are examples of converting different types of Array to String. The data types are: boolean, char, byte, short, int, long, float and double.

  • Boolean Array To String
    Here is a sample code of converting a Java boolean array to String using Arrays.toString() method:
    boolean[] boolArray = { true, false, true };
    String testString = Arrays.toString(boolArray);
    System.out.println(testString);
    
    And this is the expected output:
    [true, false, true]
    
  • Byte Array To String
    Again using Arrays.toString(), this is an example of converting a Java byte array to String:
    byte[] byteArray = { 127, -2, 31 };
    String testString = Arrays.toString(byteArray);
    System.out.println(testString);
    
    Below is the rendered output:
    [127, -2, 31]
    
  • Char Array To String
    If you have a char array, here is the code to convert a Java char array to String:
    char[] charArray = { 'z', 'a', 's' };
    String testString = Arrays.toString(charArray);
    System.out.println(testString);
    
    Here is the expected result after running the code:
    [z, a, s]
    
  • Float Array To String
    Another example, this time converting a Java float array to String:
    float[] floatArray = { 11.22f, 3.14f, 1.55f };
    String testString = Arrays.toString(floatArray);
    System.out.println(testString);
    
    This is the output when the code is run:
    [11.22, 3.14, 1.55]
    
  • Double Array To String
    Similar to float, here is the sample code to convert a Java double array to String:
    double[] doubleArray = { 5.20d, 1.5d, 10.11d };
    String testString = Arrays.toString(doubleArray);
    System.out.println(testString);
    
    And this is the expected output:
    [5.2, 1.5, 10.11]
    
  • Short Array To String
    For whole numbers, here is an example on how to convert a Java short array to String:
    short[] shortArray = { 500, -1000, 12500 };
    String testString = Arrays.toString(shortArray);
    System.out.println(testString);
    
    Below is the rendered output:
    [500, -1000, 12500]
    
  • Int Array To String
    Similar to short, here is the code to convert a Java int array to String:
    int[] intArray = { 65000, -12000, 21355 };
    String testString = Arrays.toString(intArray);
    System.out.println(testString);
    
    Here is the expected result after running the code:
    [65000, -12000, 21355]
    
  • Long Array To String
    Lastly, here is an example to convert a Java long array to String:
    long[] longArray = { 510101255, 793824123, 879683612};
    String testString = Arrays.toString(longArray);
    System.out.println(testString);
    
    This is the output when the code is run:
    [510101255, 793824123, 879683612]