Monday, September 13, 2021

How to Convert or Print Array to String in Java? Example Tutorial

Array and String are very closely related, not just because String is a character array in most of the programming language but also with popularity - they are two of the most important data structure for programmers. Many times we need to convert an array to String or create an array from String, but unfortunately, there is no direct way of doing this in Java. Though you can convert an array to String by simply calling their toString() method, you will not get any meaningful value.  If you convert an Integer array to a String, you will get something like I@4fee225 due to the default implementation of the toString() method from the java.lang.Object class. Here, I show the type of the array and content after @ is hash code value in hexadecimal.

How valuable is that? This is not what we wanted to see, I was interested in content rather than hashcode. Fortunately, Java provides a utility class called java.util.Arrays, which provides several static utility methods for arrays in Java.

For example, here we have a method to sort an array, search elements using binary search, fill the array, methods to check if two arrays are equal or not, copy a range of values from one array to another,  and much-needed toString() and deepToString() method to convert both one-dimensional and multi-dimensional array to String.

This method provides the content view of the array, for example, when you convert an integer array {1, 2, 3, 4, 5, 6, 7} to String, you will get [1, 2, 3, 4, 5, 6, 7] instead of  [I@2ab6994f , which is what most of us want to see in most of the cases.

In this article, we will see examples to convert different types of the array to String like int, char, byte, double, float, Object, and String array itself.  We will also learn how to convert a two-dimensional array to String in Java.

Btw, if you are new to Java, I suggest you first go through The Complete Java MasterClass course on Udemy. That will help you to learn fundamentals faster and you will understand this article any other article on the web better.




Array to String in Java - Example

Here is our sample Java program to convert an array to String in Java. If you want to run this program in Eclipse all you have to do is, create a Java project in Eclipse, copy this code, right-click on the src folder on your Java project in Eclipse, and the rest will be taken care of by IDE.

It will take care of creating a proper package and Java source file. You don't have to manually create the package and then Java file on your own.

In these examples, I have first shown what will happen if you call the toString() method directly or indirectly (by passing an array to System.out.print() methods) and then the right way to convert array to String by passing an array to Arrays.toString() method.

Btw, care should be taken while printing multi-dimensional arrays or converting them to String. It's not an error when you pass a multi-dimensional array to Arrays.toString() but it will not print it correctly. 

You must use the deepToString() method to convert an array that has more than one dimension, as shown in the last couple of examples of printing two and three-dimensional arrays in Java.

 Btw, if you are not familiar with an array in Java, then you should also check Java Fundamentals Part 1 and Part 2 courses on Pluralsight, two of the best courses to learn fundamental concepts in Java,  like array and String.

How to print contents of  integer array in Java




Sample Program to Print Array as String in Java

Now, let's see our Java program which prints the different kinds of the array as String in Java, like int, char, byte, short, long, float, and Object arrays:

import java.util.Arrays;

/**
 * Java Program to convert array to String in Java. In this tutorial you will
 * learn how to convert integer array, char array, double array, byte array,
 * multi-dimensional array to String in Java.
 *
 * @author Javin Paul
 */
public class ArrayToString {

    public static void main(String args[]) {

        // Converting int array to String in Java
        int[] numbers = {1, 2, 3, 4, 5, 6, 7};
        System.out.println(numbers.toString());

        String str = Arrays.toString(numbers);
        System.out.println("int array as String in Java : " + str);

        // Converting char array to String in Java
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};
        System.out.println(vowels.toString());

        String charArrayAsString = Arrays.toString(vowels);
        System.out.println("char array as String in Java : " + str);

        // Converting byte array to String in Java
        byte[] bytes = {(byte) 0x12, (byte) 0x14, (byte) 0x16, (byte) 0x20};
        System.out.println(bytes.toString());

        String byteArrayAsString = Arrays.toString(bytes);
        System.out.println("byte array as String in Java : " 
                                   + byteArrayAsString);

        // Converting float array to String in Java
        float[] floats = {0.01f, 0.02f, 0.03f, 0.04f};
        System.out.println(floats.toString());

        String floatString = Arrays.toString(floats);
        System.out.println("float array as String in Java : " + floatString);

        // Converting double array to String in Java
        double[] values = {0.5, 1.0, 1.5, 2.0, 2.5};
        System.out.println(values.toString());

        String doubleString = Arrays.toString(values);
        System.out.println("double array as String in Java : " 
                                      + doubleString);

        // Converting object array to String in Java
        Object[] objects = {"abc", "cdf", "deg", "england", "india"};
        System.out.println(objects.toString());

        String objectAsString = Arrays.toString(objects);
        System.out.println("object array as String in Java : " 
                                     + objectAsString);

        // Convert two dimensional array to String in Java
        int[][] twoD = {
            {100, 200, 300, 400, 500},
            {300, 600, 900, 700, 800},};

        System.out.println(twoD.toString());

        String twoDimensions = Arrays.deepToString(twoD);
        System.out.println("Two dimensional array as String in Java : " 
                                 + twoDimensions);

        // Convert three dimensional array to String in Java
        int[][][] threeD = {
            {
                {11, 22, 33, 44, 55},
                {32, 42, 52, 62, 72},},
            {
                {1111, 2222, 3333, 4444, 5555},
                {1001, 2001, 3001, 4001, 5001},}
        };
        System.out.println(threeD.toString());

        String threeDString = Arrays.deepToString(threeD);
        System.out.println("3 dimensional array as String in Java : " 
                                   + threeDString);

    }

}

Output
[I@2ab6994f
int array as String in Java : [1, 2, 3, 4, 5, 6, 7]
[C@3a0b2771
char array as String in Java : [1, 2, 3, 4, 5, 6, 7]
[B@324a897c
byte array as String in Java : [18, 20, 22, 32]
[F@3b8845af
float array as String in Java : [0.01, 0.02, 0.03, 0.04]
[D@5bfd9b49
double array as String in Java : [0.5, 1.0, 1.5, 2.0, 2.5]
[Ljava.lang.Object;@66de04cd
object array as String in Java : [abc, cdf, deg, england, india]
[[I@4fee225
Two dimensional array as String in Java : [[100, 200, 300, 400, 500],
 [300, 600, 900, 700, 800]]
[[[I@cde6570
3 dimensional array as String in Java : [[[11, 22, 33, 44, 55],
 [32, 42, 52, 62, 72]],
 [[1111, 2222, 3333, 4444, 5555],
 [1001, 2001, 3001, 4001, 5001]]]


You can see from the output that now instead of some memory address and type of array, you have printed the actual contents of the array in Java. This is also a good lesson on how you can print an array in readable format and you should always do this when you are logging array content or printing them.

Even Java debuggers like what is available in Eclipse, Netbeans, and IntelliJ IDEA print array like that. Currently, if you try to watch an array in Eclipse, you will see its proper content,  instead of default type@hashcode values, as seen in the following screenshot.

Array to String in Java with Example



That's all about how to convert an Array to String in Java.  As you have learned, even though the array is treated as an object in Java, it doesn't override the toString() method in a meaningful way which means you print an array into the console using System.out.println() or via any logging libraries like Log4J or SLF4j, only memory address, and type of array is printed instead of actual content, which is not helpful in most of the cases. 

But, JDK does provide methods like Arrays.toString() and Arrays.deepToString() which you can use to print elements of a single-dimensional array and multi-dimensional array in Java.

Whenever you print an array, use those methods depending upon which kind of array you are printing because passing a multi-dimensional array to Arrays.toString() will only print top-level array which is again memory address and type of nested array, means not useful at all.


Do you want to Master the String data structure in Java? Check out these amazing String tutorials to learn more about various String functionalities :
Thanks for reading this article so far. If you like this Array to String tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are looking to learn Data Structure and Algorithms from scratch or want to fill gaps in your understanding and looking for some free courses, then you can check out this list of Free Algorithms Courses to start with.

4 comments:

  1. I remember, in one of our project we need to convert array of String to one String where each element is separated with comma. It was simple to do, just iterate throught Array and use an Stringbuffer to append each element at the end after comma.

    ReplyDelete
  2. String charArrayString = Arrays.toString(vowels);
    System.out.println("char array as String in java :" + charArrayString);

    ReplyDelete
  3. int[] number = {1,23,456,78910};

    // prints "[1, 23, 456, 78910]"
    String str = Arrays.toString(number);

    // prints "1, 23, 456, 78910"
    String str2 = Arrays.toString(number).substring(1, (Arrays.toString(number).length() - 1));

    // prints "12345678910"
    String str3 = Arrays.toString(number).substring(1, (Arrays.toString(number).length() - 1)).replaceAll(", ", "");


    System.out.println(str);
    System.out.println(str2);
    System.out.println(str3);

    ReplyDelete
  4. Correct code:

    import java.util.Arrays;

    public class ArrayToString {

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {

    // Converting int array to String in Java
    int[] numbers = {1, 2, 3, 4, 5, 6, 7};
    System.out.println(numbers.toString());
    String str = Arrays.toString(numbers);
    System.out.println("int array as String in Java : " + str);

    // Converting char array to String in Java
    char[] vowels = {'a', 'e', 'i', 'o', 'u'};
    System.out.println(vowels.toString());
    String charArrayAsString = Arrays.toString(vowels);
    System.out.println("char array as String in Java : " + charArrayAsString);

    // Converting byte array to String in Java
    byte[] bytes = {(byte) 0x12, (byte) 0x14, (byte) 0x16, (byte) 0x20};
    System.out.println(bytes.toString());
    String byteArrayAsString = Arrays.toString(bytes);
    System.out.println("byte array as String in Java : " + byteArrayAsString);

    // Converting float array to String in Java f
    Float[] floats = {0.01f, 0.02f, 0.03f, 0.04f};
    System.out.println(floats.toString());
    String floatString = Arrays.toString(floats);
    System.out.println("float array as String in Java : " + floatString);
    }
    }

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.