How to initialize a 3d array in Java?

How to initialize a 3d array in Java?

To initialize a 3D array in Java, you can use the new operator to create an array and then use nested loops to fill the array with values. Here is an example of how you might do this:

refer t‮ual:o‬tturi.com
int[][][] array = new int[3][3][3];

for (int i = 0; i < 3; i++) {
  for (int j = 0; j < 3; j++) {
    for (int k = 0; k < 3; k++) {
      array[i][j][k] = i + j + k;
    }
  }
}

This code creates a 3D array called array with dimensions 3x3x3, and fills the array with values using three nested for loops. The resulting array will look like this:

array[0][0][0] = 0 + 0 + 0 = 0
array[0][0][1] = 0 + 0 + 1 = 1
array[0][0][2] = 0 + 0 + 2 = 2
array[0][1][0] = 0 + 1 + 0 = 1
array[0][1][1] = 0 + 1 + 1 = 2
...

You can also use an array literal to initialize the array with specific values:

int[][][] array = {
  {
    {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}
  }
};

This code creates a 3D array called array with dimensions 3x3x3 and initializes it with the values shown. The resulting array will look like this:

array[0][0][0] = 1
array[0][0][1] = 2
array[0][0][2] = 3
array[0][1][0] = 4
array[0][1][1] = 5
...

You can also use the Arrays.fill() method from the java.util.Arrays class to fill the array with a specific value:

int[][][] array = new int[3][3][3];
Arrays.fill(array, 0);  // Fill the array with zeros

This code creates a 3D array called array with dimensions 3x3x3 and fills it with zeros using the Arrays.fill() method. The resulting array will contain all zeros.

Created Time:2017-11-01 20:42:48  Author:lautturi