Let us go through a three dimensional array in java language. Before that, you may go through the following topic in java.
Three Dimensional (3D) Array program
3D arrays are the multidimensional array in java. They are quite complicated as they run on three loops. In order to initialize or display the array, we need three loops. The inner loop is for one dimensional array, the second one is for the two dimensions and the outer loop makes the third dimensional array.
The program below is an example of 3d array in java. We will initialize the 3D array and display the output on the screen.
Three Dimensional Array Program in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | import java.util.Scanner; public class Main { public static void main(String args[]) { int i, j, k, index_1, index_2, index_3; Scanner sc = new Scanner(System.in); System.out.print("Enter the Index 1 for Array: "); index_1 = sc.nextInt(); System.out.print("Enter the Index 2 for Array: "); index_2 = sc.nextInt(); System.out.print("Enter the Index 3 for Array: "); index_3 = sc.nextInt(); int arr[][][] = new int[index_1][index_2][index_3]; System.out.print("\nEnter the elements: \n"); for (i = 0; i < index_1; i++) { for (j = 0; j < index_2; j++) { for (k = 0; k < index_3; k++) { System.out.print("arr[" + i + "][" + j + "][" + k + "]: "); arr[i][j][k] = sc.nextInt(); } } } //Display the elements System.out.print("\nThe enetered elements are: \n"); for (i = 0; i < index_1; i++) { for (j = 0; j < index_2; j++) { for (k = 0; k < index_3; k++) System.out.print("arr[" + i + "][" + j + "][" + k + "]: " + arr[i][j][k] + "\n"); } } } } |
Output:
Enter the Index 1 for Array: 2
Enter the Index 2 for Array: 2
Enter the Index 3 for Array:
Enter the elements:
arr[0][0][0]: 1
arr[0][0][1]: 2
arr[0][1][0]: 3
arr[0][1][1]: 4
arr[1][0][0]: 5
arr[1][0][1]: 6
arr[1][1][0]: 7
arr[1][1][1]: 8
The enetered elements are:
arr[0][0][0]: 1
arr[0][0][1]: 2
arr[0][1][0]: 3
arr[0][1][1]: 4
arr[1][0][0]: 5
arr[1][0][1]: 6
arr[1][1][0]: 7
arr[1][1][1]: 8