Back to 2D Arrays

Lesson PreviewLesson 2 of 3 in this unit

8.2 Traversing 2D Arrays

Part of 2D Arrays in AP® Computer Science A. Read the opening section, then create a free account for the full interactive lesson, practice, and progress tracking.

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

java
//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

Continue the full lesson in Stellar

Create a free account to unlock the remaining sections, checkpoints, course practice, and progress tracking for AP® Computer Science A.