Print an Array using Java

thumbnail

In this tutorial, you will learn about different techniques to print elements from a given array using Java. There will be 3 example that shows to you, such as: Print an Array using standard library Arrays, Print an Array using For-loop, and Print a Multi-dimensional array.

Example 1: Print an Array using Standard Library

In the first example, the output will be printed by single line of code using Arrays.toString() function. This is the easiest way to print an array.

import java.util.Arrays;

public class Example1 {
    public static void main(String[] args) {
        int[] array = {1, 3, 5, 7, 9};
        System.out.println(Arrays.toString(array));
    }
}

The output will be:

[1, 3, 5, 7, 9]

Example 2: Print an Array using For-loop

The second example will be about printing array value using for-loop. The for-each loop is used to iterate over the given array.  It accesses each element in the array and print using println().

public class Example2 {
    public static void main(String[] args) {
        int[] array = {0, 2, 4, 6, 8};
        for (int element: array) {
            System.out.println(element);
        }
    }
}

The output will be in five lines because we use println():

0
2
4
6
8

Example 3: Print a Multi-dimensional Array

import java.util.Arrays;

public class Example3 {
    public static void main(String[] args) {
        int[][] array = {{1, 2}, {3, 4}, {5, 6, 7}};
        System.out.println(Arrays.deepToString(array));
    }
}

The output will be:

[[1, 2], [3, 4], [5, 6, 7]]

Since each element in array contains another array, we can use Arrays.toString() to print the address of the elements (nested array). To get the number from the inner array, we can also use Arrays.deepToString() function. This gets us the number 1,2 and so on. The function also works for 3-dimensional arrays.

You can find another tutorial about java through this link.

Back To Top