Getting the Length of an Array

suggest change

An array object holds a fixed number of elements of one type. That number is chosen when the array is created and cannot be changed.

int[] arr1 = new int[0];
int[] arr2 = new int[2];
int[] arr3 = new int[]{1, 2, 3, 4};
int[] arr4 = {1, 2, 3, 4, 5, 6, 7};

int len1 = arr1.length; // 0
int len2 = arr2.length; // 2
int len3 = arr3.length; // 4
int len4 = arr4.length; // 7

The length field in an array stores the size of an array. It is a final field and cannot be modified.

This code shows the difference between an array's length and how many of its slots hold a non-null reference. Null slots are empty. They still count toward length.

public static void main(String[] args) {
    Integer arr[] = new Integer[] {1,2,3,null,5,null,7,null,null,null,11,null,13};

    int arrayLength = arr.length;
    int nonEmptyElementsCount = 0;

    for (int i=0; i<arrayLength; i++) {
        Integer arrElt = arr[i];
        if (arrElt != null) {
            nonEmptyElementsCount++;
        }
    }

    System.out.println("Array 'arr' has a length of "+arrayLength+"\n"
                            + "and it contains "+nonEmptyElementsCount+" non-empty values");
}

Result:

Array 'arr' has a length of 13
and it contains 7 non-empty values

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents