2D Array Length

Two Dimensional Arrays

2D Array Length

🙋 Need help? Ask an expert now!

Now we will take a look at the properties of the rows and columns that make up 2D arrays. Most of the time, each row in a 2D array will have the same number of columns, but that may not always be the case. If you were to initialize a 2D array by listing out the elements individually, it may lead to a row with a different number of columns. In situations like this, and others, you will need to know how to access the length of the row or the column of a 2D array. Let's see how it's done below.

ArrayLength2DExample.java
package exlcode;

public class ArrayLength2DExample {

  public static int[][] exampleVariableOne = new int[10][5];
  // returns the length of the rows in the array
  public static int lengthOne = exampleVariableOne.length;
  // returns the length of the columns in the array
  public static int lengthTwo = exampleVariableOne[0].length;

  public static void main(String[] args) {
    System.out.println(lengthOne);
    System.out.println(lengthTwo);
  }
}

We use arrayname.length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.

When calling the length of a column, we pinpoint the row before using .length. The program above checks to see how many columns the first row of the 2D array contains by calling exampleVariableOne[0].length. Adjust the '0' to another number to change the row specified.

Edit Me on GitHub!

Application Question

Consider the following code segment:

int[][] varOne = {{1, 2, 3, 6}, {5, 8, 9, 10}, {7, 6, 7, 8}};
System.out.println(varOne[1].length);

What is printed as a result of executing this code segment?