English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn different techniques to print the elements of a given array in Java.
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.
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.
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.