2D Array Length Java

Java

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.


Related post

Iterating Through 2D Array Java

Java, , , , ,

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, …

Read more