how to fill a 2d array in java

www.‮‬lautturi.com
how to fill a 2d array in java

To fill a 2D array in Java, you can use a loop to iterate over the elements of the array and assign a value to each element.

Here's an example of how to fill a 2D array of integers in Java:

int[][] array = new int[3][3];

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

In the above example, a nested loop is used to iterate over the elements of the array and assign a value to each element. The outer loop iterates over the rows of the array, and the inner loop iterates over the columns.

You can also use an array initializer to fill a 2D array with a set of values. For example:

int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

This creates a 2D array of integers with the values 1, 2, 3, 4, 5, 6, 7, 8, and 9.

Keep in mind that the size of a 2D array is fixed and cannot be changed once it is created. To change the size of a 2D array, you can create a new array with the desired size and copy the elements from the old array to the new one.

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