Length of Arrays
The following example demonstrates how to get the length of an array in Java. To do this, you use the length property.
With a one-dimensional array, it's simple — its length is the total number of elements.
The length of a multidimensional array in Java is the number of elements in its first dimension. For example, the length of array2
is 2. You can also retrieve the length of any specific row. For instance, array2[0].length
returns the number of elements in the row at index 0.
public class ArraySizeExample {
public static void main(String[] args) {
int[] array1 = {1, 2, 3, 4};
int[][] array2 = {{1, 1, 1}, {2, 2, 2}};
System.out.println("Length of array1 = " + array1.length);
System.out.println("Length of array2 = " + array2.length);
System.out.println("Length of first row in array2 = " + array2[0].length);
}
}
Output:
Length of array1 = 4
Length of array2 = 2
Length of first row in array2 = 3

Please log in or register to have a possibility to add comment.