Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
2D Array Length
Introduction To Java Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Introduction To Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
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.