Skip to content

Array Length vs. Capacity

Array capacity is how many items an array can hold, and array length is how many items an array currently has.

ggorantala
ggorantala
1 min read

Table of Contents

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 an array has?

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[10];

Let's insert integers 1, 2, 3, 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.

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.lengthwhere 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
ArraysData Structures and Algorithms

ggorantala Twitter

Gopi has a decade of experience with a deep understanding of Java, Microservices, and React. He worked in India & Europe for startups, the EU government, and tech giants.

Comments


Related Posts

Members Public

Arrays From Zero To Mastery: A Complete Notes For Programmers

This article discusses array data structure with sketches, memory diagrams, array capacity vs. length, strengths & weaknesses, big-O complexities, and more!

Members Public

Find Even Number Of Digits in an Array

This problem tests your knowledge of mathematics. Solving this problem helps you find the place values and how they are represented in the decimal number system.

Members Public

Array Strengths, Weaknesses, and Big-O Complexities

In this lesson, you will learn about array strengths and weaknesses along with the big-o complexities.