Coding Rooms transition to “read-only” state on August 31, 2024  Click here for more information.

Iterating Through 2D Array Java

Learn how to iterate through a 2D array in Java

October 5, 2020
by
Sasha Varlamov

We explored using for loops with one-dimensional arrays. Now let’s jump into nested for loops as a method for iterating through 2D arrays. A nested for loop is one for loop inside another. Take a look below to see what this means.

Iteration2DExample.java
package exlcode;

public class Iteration2DExample {

  public static int[][] exampleVariableOne = {{0, 1, 2, 3, 4}, {4, 5, 6, 7, 8}};

  public static void main(String[] args) {
    // nested for loops are necessary for
    // iterating through a 2D array
    for (int countOne = 0; countOne < exampleVariableOne.length; countOne++) {
      for (int countTwo = 0; countTwo < exampleVariableOne[countOne].length; countTwo++) {
        System.out.print("Index [" + countOne + "][" + countTwo + "]: ");
        System.out.println(exampleVariableOne[countOne][countTwo]);
      }
    }
  }
}

The first for loop loops through each row of the 2D array one by one. As the first loop runs through each row, the second (nested) for loop inside the first loop loops through the columns one by one. The nested for loops runs row by row, checking each column within the row before moving on to the next row.

Because each row could have different numbers of columns, we need to access the specific column length of the specified row. That is why you see exampleVariableOne[countOne].length used within the second nested for loop.

The concept of using loops when working with 2D arrays is an essential tool in every programmer’s toolkit. Look meticulously through the code above and become comfortable with how each loop fits into the big picture. When you become comfortable with the for loop, try using “for-each” loops with 2D arrays.

Sasha Varlamov
Sasha Varlamov

Coding Rooms
Founder and CEO

October 5, 2020

Learn why these organizations choose Coding Rooms as their next-generation learning platform.