To traverse through all elements of a 2D array, we often use nested loops. The outer loop iterates through the rows, and the inner loop iterates through the columns.
Before we get into traversing 2D arrays, let's learn how its length method works. The expression .length returns the number of rows in the 2D array. This is because a 2D array in Java is an array of arrays, where each row is a separate one-dimensional array. To get the number of columns in a specific row, use [row].length
//4 columns and 3 rows
int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// matrix.length returns the total number of rows in the 2D array
System.out.println("matrix.length (number of rows): " + matrix.length);
// matrix[0].length returns the number of columns in the first row
System.out.println("matrix[0].length (number of columns in row 0): " + matrix[0].length);
Output
matrix.length (number of rows): 3 matrix[0].length (number of columns in row 0): 4