Java Index through 2d array

Java Index through 2d array

To index through a 2D array in Java, you can use a loop with two variables, one for the outer array and one for the inner array. Here's an example:

refe‮ r‬to:lautturi.com
int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

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

This will print out the elements of the array one by one, from left to right and top to bottom.

Alternatively, you can use an enhanced for loop to iterate through the 2D array:

for (int[] innerArray : array) {
  for (int element : innerArray) {
    System.out.println(element);
  }
}

This will have the same effect as the previous example.

Created Time:2017-11-03 23:27:08  Author:lautturi