Print Array Elements in Java

In this post, you will learn to print array elements in Java in the following ways:

  • Using the Arrays.toString() method
  • With a for-loop

Look at the Java Arrays tutorials page to learn more about Arrays and how to work with them. 

Print array elements in Java using the Arrays.toString() method

The Arrays class has a static method toString() that returns a string representation of the provided array.
It contains multiple overloaded versions of the toString() method:

static String toString(short[] a)
static String toString(byte[] a)
static String toString(char[] a)
static String toString(double[] a)
static String toString(float[] a)
static String toString(boolean[] a)
static String toString(int[] a)
static String toString(long[] a)
static String toString(Object[] a)


Example

class PrintArrayElementsExample {

  public static void main(String[] args) {

    int[] arr1 = {1, 7, 9, 5, 2, 8, 3};

    String[] arr2 = {"Megan", "Tom", "Melissa", "John", "Steve"};

    // print elements of the arr1
    System.out.println(Arrays.toString(arr1));

    // print elements of the arr2
    System.out.println(Arrays.toString(arr2));

  }
}
Output: [1, 7, 9, 5, 2, 8, 3] [Megan, Tom, Melissa, John, Steve]

Print array elements with a for-loop

We can always use the for-loop to iterate over an array and print the elements, like in the following example:

class PrintArrayElementsExample {

  public static void main(String[] args) {

    String[] names = {"Megan", "Tom", "Melissa", "John", "Steve"};

    // standard for loop
    for (int i = 0; i < names.length; i++) {
      System.out.print(names[i] + " ");
    }
    
    System.out.println();
    // enhanced for loop - recommended
    for (String name : names) {
      System.out.print(name + " ");
    }
 
 }
}
Output: Megan Tom Melissa John Steve Megan Tom Melissa John Steve

Printing the elements of a multi-dimensional array

We can print the elements of a multi-dimensional array using the static deepToString(Object[] a) method that returns a string representation of the “deep contents” of the specified array.

Example

class PrintArrayElementsExample {

  public static void main(String[] args) {

    String[][] cities = {{"New York", "Boston"}, {"London", "Birmingham"}, {"Paris", "Marseille"}};

    // print the elements
    System.out.println(Arrays.deepToString(cities));

  }
}
Output: [[New York, Boston], [London, Birmingham], [Paris, Marseille]]
 
I hope this tutorial was helpful to you. There are many more tutorials that teach how to work with arrays.  To begin with, have a look at the Java Arrays tutorial. 
 
Happy learning!

Leave a Reply

Your email address will not be published.