Skip to main content

Arrays Overview

Capacity vs. Length

Learn the crucial difference: Array capacity = maximum items it can hold, Array length = current items stored. Master A.length attribute, memory allocation, and avoid common coding mistakes with practical examples.

How long is an array?

If someone asks you how long an array is, there could be two possible answers when discussing how long an array is.

  1. How many items can an array hold, and
  2. How many items currently does an array have?

The first point is about capacity, and the second is about length.

Let us create an array A[10], whose capacity is10, but no items are added. Technically, we can say the length is 0.

int[] A = new int[0];
Figure 1 - Array with capacity of N elements
Figure 1 - Array with capacity of N elements

Let's insert integers 123, and 4 into the above array.

A[0] = 1;
A[1] = 2;
A[2] = 3;
A[3] = 4;

At this point, the length/size of the array is 4 and the capacity of the array that has room to store elements is 10.

The following code snippets explain the difference between array length vs. capacity.

Figure 2 - Array of 10 elements explaining capacity vs size
Figure 2 - Array of 10 elements explaining capacity vs size

Capacity

The capacity of an array in Java can be checked by looking at the value of its length attribute. This is done using the code A.length, where A the Array's name is.

public class ArrayCapacityLength {
    public static void main(String[] args) {
        int[] A = new int[10];

        System.out.println("Array Capacity " + A.length); // 10
    }
}

Running the above snippet gives:

Array Capacity is 10

Length

This is the number of items currently in the A[] array.

import java.util.Arrays;

public class ArrayCapacityLength {
    public static void main(String[] args) {
        int[] A = new int[10];

        int currentItemsLength = 0;
        for (int i = 0; i < 4; i++) {
            currentItemsLength += 1;
            A[i] = i + 10;
        }

        System.out.println(Arrays.toString(A)); // [10, 11, 12, 13, 0, 0, 0, 0, 0, 0]
        System.out.println("Array length is " + currentItemsLength); // 4
        System.out.println("Array Capacity is " + A.length); // 10
    }
}

Running the above snippet gives

Array length is 4
Array Capacity is 10