Print Array Elements in Java

This tutorial covers how to display the elements of an array in Java, in two different ways:

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

Explore the Java Arrays tutorials to learn more about how to use and manage arrays.

Print array elements using the Arrays.toString() method

The Array class includes a static method called toString() that converts an array into a string representation. This method has various variations available.

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 using a for-loop

The for-loop can be used to iterate through an array and display its elements as shown 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

Print multi-dimensional array elements

The static method deepToString(Object[] a) can be used to display the elements of a multi-dimensional array, this method returns a string representation of the elements contained within 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 you found this tutorial informative. There are many additional resources available that can help you learn how to work with arrays, a good starting point would be the Java Arrays tutorial.
 
Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *