java array length feature imagejava array length feature image
HappyCoders Glasses

Array Length in Java

Sven Woltmann
Sven Woltmann
Last update: November 27, 2024

In this article, you will learn:

  • How to find out the length of an array in Java,
  • How to define the length of an array in Java,
  • How much memory space an array occupies on the heap,
  • And what the maximum size of an array is in Java.

We consider both one-dimensional and 2D arrays.

How to Find the Length of an Array in Java?

Let’s assume we get a Java array as follows:

String[] names = getNames();Code language: Java (java)

Then we find out the length of this array, i.e., the number of entries in it, as follows:

int numberOfCustomers = customers.length;Code language: Java (java)

How to Get the Length of a 2D Array in Java?

With a two-dimensional array, things get a little more complicated. In Java, a two-dimensional array is an array of arrays. A matrix of height two and width three would be represented like this:

Java 2D array

We can now determine the height and width as follows:

int[][] intMatrix = getMatrix();
int height = intMatrix.length;
int width = intMatrix[0].length;Code language: Java (java)

The height is the length of the array (i.e., the number of rows the matrix contains), and the width is the length of the first row.

Please note, however, that with a two-dimensional array in Java, all sub-arrays do not necessarily have to be the same length. A 2D array could also look like this:

Java 2D array with sub-arrays of different lengths

Here, we could calculate statistics on the line lengths:

int[][] twoDimensionalArray = {{2, 3, 6}, {4, 5, 1, 9, 7}};
IntSummaryStatistics statistics = 
    Arrays.stream(twoDimensionalArray).mapToInt(row -> row.length).summaryStatistics();
System.out.println(statistics);
Code language: Java (java)

The following result would be output for the example matrix shown above:

IntSummaryStatistics{count=2, sum=8, min=3, average=4.000000, max=5}Code language: plaintext (plaintext)

We have two lines, the sum of the lengths is 8 (that's right: 5 plus 3), the minimum is 3, the average size is 4, and the maximum is 5.

How to Set the Array Length in Java?

The length of an array is defined when it is initialized. The following code, for example, creates a string array of size four:

String[] fruits = {"jujube", "apple", "boysenberry", "cherry"};Code language: Java (java)

We can also define a string array of the same size as follows:

String[] fruits = new String[4];Code language: Java (java)

However, this array does not yet contain any values; is initialized with null at each position. You can learn about initializing strings in the article How to Initialize Arrays in Java.

After initialization, we can no longer change the array length.

How To Set the Length of a 2D Array in Java?

You can also define the length of a 2D array in the two ways shown above – i.e., with predefined values:

int[][] twoDimensionalArray = {{2, 3, 6}, {4, 5, 1, 9, 7}}Code language: Java (java)

This code creates the two-dimensional array shown above with sub-arrays of different lengths.

And secondly, with default values (0 in the case of the type int):

int[][] twoDimensionalArray = new int[2][3];Code language: Java (java)

This code creates the following array:

Java 2D array matrix with zeros

You can learn more about initializing 2D arrays in the article How to Initialize Arrays in Java.

How Much Memory Does a Java Array Take Up?

In the following, we look at the memory layout for Compressed Class Pointers and Compressed OOPs, the standard setting on 64-bit machines as of Java 22 (before the header is further compressed by Project Lilliput).

An array is an object in Java; therefore, like any other object, it has a 12-byte object header. This is followed by four bytes in which the length of the array is stored. This is followed by the actual elements of the array in sequential order.

For example, the int array [6, 1, 1, 5, 7] is stored in the memory as follows:

Java int array memory layout

The last four bytes marked with “padding” are not really part of the array but cannot be used in any other way either, as objects in the Java heap are stored at memory addresses divisible by eight when using compressed oops. This is because, with 32 bits, we can address not just 232 bytes, i.e. 4 GB, but eight times as many, i.e. 32 GB.

Elements in primitive arrays each occupy the following memory space:

  • boolean and byte: 1 byte each
  • short and char: 2 bytes each
  • int and float: 4 bytes each
  • long and double: 8 bytes each

With short instead of int values, the array would have the following layout:

java short array memory layout

And with byte elements, it would have the following layout:

java byte array memory layout

We can calculate the total size of an array as follows:

Total size = align(12 bytes + 4 bytes + number of elements × size of element type in bytes)

The align function rounds the result up to the next value divisible by eight so that the result contains the “wasted” space.

This results in the following size for the int array with five elements:

Total size = align(12 bytes + 4 bytes + 5 × 4 bytes)
= align(36 bytes)
= 40 bytes

If we were to store the same five elements in a long array, it would have the following size:

Total size = align(12 bytes + 4 bytes + 5 × 8 bytes)
= align(56 bytes)
= 56 bytes

With object arrays, it is not the objects themselves that are stored in the array but the references to the objects. The following graphic shows the memory layout of the string array shown above:

Java string array memory layout

I have not shown the object layout of the strings themselves here, as this article is primarily about arrays, not strings. The strings also have a header, several fields, and a reference to a byte array, which in turn contains a header, a length field, and the actual characters of the string.

How Much Memory Does a 2D Array Take up in Java?

As you have seen above, a two-dimensional array is actually an array of arrays. Therefore, we must add the memory space of the outer array and that of all the inner arrays.

The array from the example shown above has the following memory layout:

Java 2D array memory layout

We can calculate the total size of this 2D array as follows:

Total size = align(12 bytes + 4 bytes + number of lines × 4 bytes)
+ number of rows × align(12 bytes + 4 bytes + number of columns × size of element type in bytes)

For the example matrix with two rows and three columns, the following results:

Total size = align(12 bytes + 4 bytes + 2 x 4 bytes) + 2 × align(12 bytes + 4 bytes + 3 × 4 bytes)
= align(24 bytes) + 2 × align(28 bytes)
= 24 bytes + 2 × 32 bytes
= 88 bytes

Max Array Size in Java

Java arrays use an int for the index, meaning the theoretical upper limit is Integer.MAX_VALUE, i.e., 2,147,483,647 elements.

According to the formula above, an int array of this size would occupy just over 8 GB. That shouldn’t be a problem for most modern computers.

When I try to create an array of this size – no matter which primitive type I use – I get the following error:

Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit

Only when I reduce the size by two to 2,147,483,645, does it work – and again with all primitive data types, even with long. The limit, therefore, has nothing to do with the available memory but is determined by the VM.

The following table shows the maximum array size for all primitive types – both in terms of the number of elements and the heap memory occupied on my VM:

TypesMaximum elementsMaximum size in the heap
boolean, byteInteger.MAX_VALUE - 22,147,483,664 bytes (~ 2 GB)
short, charInteger.MAX_VALUE - 24,294,967,312 bytes (~ 4 GB)
int, floatInteger.MAX_VALUE - 28,589,934,600 bytes (~ 8 GB)
long, doubleInteger.MAX_VALUE - 217,179,869,176 bytes (~ 16 GB)

Max Size of a 2D Array in Java

The upper limit described in the previous chapter applies to each array dimension. Theoretically, the following sizes would, therefore, be possible with two-dimensional arrays:

TypesMaximum elementsMaximum size in the heap
boolean, byte(Integer.MAX_VALUE - 2)²~ 4 exabytes (= 4 million terabytes)
short, char(Integer.MAX_VALUE - 2)²~ 8 exabytes (= 8 million terabytes)
int, float(Integer.MAX_VALUE - 2)²~ 16 exabytes (= 16 million terabytes)
long, double(Integer.MAX_VALUE - 2)²~ 32 exabytes (= 32 million terabytes)

In this case, the size is not limited by the VM but by the available memory or the memory that the garbage collector can manage (e.g., 16 TB for the ZGC).

Conclusion

We can find the length of an array using array.length. We can only set the length of an array when it is created; we cannot change it afterward.

With compressed pointers, arrays have a 12-byte object header and a 4-byte length field, followed by the actual data (1 byte per byte/boolean, 2 bytes per short/char, 4 bytes per int/float or object reference, and 8 bytes per long/double).

An array can contain a maximum of Integer.MAX_VALUE - 2 elements (on most VMs), regardless of the type of array elements.

If you liked the article, share it using one of the share buttons at the end or leave me a comment.

Would you like to know when new articles get published on HappyCoders.eu? Then click here to sign up for the HappyCoders.eu newsletter.