How to Get the Length of a 2D Array in Java

Hassan Saeed Feb 02, 2024
  1. Get Length of a 2D Array With Fix Column Size in Java
  2. Get Length of a 2D Array With Variable Column Size in Java
How to Get the Length of a 2D Array in Java

This tutorial discusses methods to get the length of a 2D array in Java.

A 2D array in Java is an array of arrays i.e., an array whose element is another array. For example, test = new int[5][10]; represents an array that contains five elements, and each of these five elements represents an array containing 10 int elements. The 2D array can either be considered a rectangular grid where the number of columns is the same in each row or a ragged array where the number of columns differs in each row.

We might be interested in getting the number of rows in a 2D array or the number of columns in each row of the 2D array. Below we will discuss how to get that.

Get Length of a 2D Array With Fix Column Size in Java

If we know that a 2D array is a rectangular grid, we can get the number of rows using arr.length and the number of columns using arr[0].length. The below example illustrates this.

public class MyClass {
  public static void main(String args[]) {
    int[][] test;
    test = new int[5][10];
    int row = test.length;
    int col = test[0].length;

    System.out.println("Rows: " + row);
    System.out.println("Columns: " + col);
  }
}

Output:

Rows: 5
Columns: 10

Get Length of a 2D Array With Variable Column Size in Java

If a 2D array does not have a fixed column size i.e., each array contained in the array of arrays is of variable length, we can still use arr.length to get the number of rows. However, to get the number of columns, you will have to specify which row you want to get the column length for: arr[rowNumber].length. The below example illustrates this.

public class MyClass {
  public static void main(String args[]) {
    int[][] test;
    test = new int[2][];
    test[0] = new int[5];
    test[1] = new int[10];
    int row = test.length;
    int col_1 = test[0].length;
    int col_2 = test[1].length;

    System.out.println("Rows: " + row);
    System.out.println("Columns of first row: " + col_1);
    System.out.println("Columns of second row: " + col_2);
  }
}

Output:

Rows: 2
Columns of first row: 5
Columns of second row: 10

Related Article - Java String