English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Online Tools

Each loop

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Exception Handling

resources

Java List (List)

Java Queue (queue)

Java Map collection

Java Set collection/Java Input Output (I

Java Reader/Writer

Java other topics

Java program to print the array

Comprehensive Java Examples

In this program, you will learn different techniques to print the elements of a given array in Java.

Example1Using For loop to print the array

public class Array {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        for (int element : array) {
            System.out.println(element);
        }
    }
}

When the program is run, the output is:

1
2
3
4
5

In the above program, for-The each loop is used to iterate over the given array array.

It accesses each element within and uses println() to print the array.

Example2Using the standard library array to print the array

import java.util.Arrays;
public class Array {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        System.out.println(Arrays.toString(array));
    }
}

When the program is run, the output is:

[1, 2, 3, 4, 5]

In the above program, the for loop has been replaced with a single line of code using the Arrays.toString() function.

As you can see, this provides a clean output without any additional code lines.

Example3Print multidimensional array

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

When the program is run, the output is:

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

In the above program, since each element of the array contains another array, only Arrays.toString() is used to print the address of the element (nested array).

To get numbers from the internal array, we only need another function Arrays.deepToString(). This gives us the number1,2and so on, we are looking for.

This function also applies to3Dimensional array.

Comprehensive Java Examples