To loop through the elements of a two-dimensional (2D) array in Java, you can use a nested for
loop. A nested loop is a loop that is contained within another loop.
Here is an example of how you can use a nested for
loop to iterate through the elements of a 2D array and print them:
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 the elements of the array in row-major order, which means that the elements of each row are printed before the elements of the next row.
You can also use the for-each
loop to iterate through the elements of a 2D array, like this:
int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; for (int[] row : array) { for (int element : row) { System.out.println(element); } }
Keep in mind that the size of each row in a 2D array does not have to be the same, so you will need to use the length
property of each row to determine the number of elements in the row.
You can also use the Arrays.deepToString
method to convert the 2D array to a string representation, like this:
int[][] array = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; System.out.println(Arrays.deepToString(array));