Coding Rooms is discontinuing Free and K-12 services. Click here for more information.

2D Array Length Java

Learn how to get the length of a 2D array in Java

October 3, 2020
Sasha Varlamov

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:
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) {

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.

Sasha Varlamov
Sasha Varlamov

Coding Rooms
Founder and CEO

October 3, 2020

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