Java Language Getting the Length of an Array

Download Java Language for free


Arrays are objects which provide space to store up to its size of elements of specified type. An array's size can not be modified after the array is created.

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 the length of an array and amount of objects an array stores.

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) {

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


Array 'arr' has a length of 13
and it contains 7 non-empty values
How do you change the size of an array?