Skip to content

Java Array Length and Size: .length, 2D Arrays, Max Array Size

A steel vernier caliper against butter yellow, its jaws resting exactly against the two ends of a horizontal glass tube; inside the tube, a row of equally sized coral-red spheres

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();

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

int numberOfNames = names.length;

Note that length is a field on arrays, not a method call – unlike String.length() or List.size(). If you write names.length(), the compiler reports an error.

If you only have an array as an Object, for example in generic code, java.lang.reflect.Array.getLength(array) returns its length.

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:

Two-dimensional int array intMatrix: the outer array holds two references pointing to two inner arrays with the values 2, 3, 6 and 4, 5, 1
A matrix with two rows and three columns as an array of two arrays

We can now determine the height and width as follows:

int[][] intMatrix = getMatrix();
int height = intMatrix.length;
int width = intMatrix[0].length;

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.

If the matrix has no rows, intMatrix[0] throws an ArrayIndexOutOfBoundsException – in that case, check beforehand that height is greater than 0.

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

Two-dimensional int array twoDimensionalArray with sub-arrays of different lengths: the first reference points to an array with the values 2, 3, 6, the second to an array with the values 4, 5, 1, 9, 7
A 2D array with one row of length 3 and one row of length 5

Here, we could calculate statistics on the row 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);

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

IntSummaryStatistics{count=2, sum=8, min=3, average=4.000000, max=5}

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

By the way, IntSummaryStatistics.toString() formats the average with String.format() and therefore depending on the locale – on a system with a German language setting, it prints average=4,000000.

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"};

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

String[] fruits = new String[4];

However, this array does not yet contain any values; it is initialized with null at each position. You can learn all about initializing arrays 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}};

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

This code creates the following array:

Two-dimensional int array twoDimensionalArray with two rows and three columns, all values 0
new int[2][3] creates two rows of three zeros each

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 with compact object headers, which have been enabled by default since Java 27, and with compressed oops, i.e., compressed object references – the default setting on 64-bit machines with a heap of up to 32 GB.

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

The following diagram shows how the int array [6, 1, 1, 5, 7] is stored in memory up to Java 26 and how it has been stored since Java 27:

Memory layout of an int array with five elements: up to Java 26 with a 12-byte header, length field from byte 12, elements from byte 16, and four bytes of padding, 40 bytes in total – since Java 27 with an 8-byte header, length field from byte 8, and elements from byte 12, 32 bytes in total
Compact object headers save eight bytes on an int array with five elements – 40 bytes become 32

You can see that the smaller header saves eight bytes on this array – 40 bytes become 32. Up to Java 26, the elements ended at byte 36, and the last four bytes were padding – filler bytes that are not part of the array but cannot be used in any other way either; the following info box explains why. Since Java 27, the five int values fill the space up to byte 32 exactly.

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:

Memory layout of a short array with five elements: 8-byte header, length field from byte 8, five 2-byte elements from byte 12, and two bytes of padding, 24 bytes in total
A short array with five elements takes up 24 bytes – ten bytes of data and two bytes of padding

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

Memory layout of a byte array with five elements: 8-byte header, length field from byte 8, five 1-byte elements from byte 12, and seven bytes of padding, 24 bytes in total
A byte array with five elements also takes up 24 bytes – five bytes of data and seven bytes of padding

With long and double elements, there is one more thing to consider: 8-byte values must be stored at addresses divisible by eight so that the CPU can read and write them in a single memory access – unaligned 8-byte accesses are slower on some processor architectures and not allowed at all on others. The elements therefore do not start at byte 12 but at byte 16 – the four bytes in between remain unused.

Memory layout of a long array with five elements: 8-byte header, length field from byte 8, four bytes of padding, and five 8-byte elements from byte 16, 56 bytes in total
In a long array, the padding sits between the length field and the data – the elements start at byte 16

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

Total size = align(8 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 padding. In long and double arrays, the elements start at byte 16; there, the formula is Total size = 16 bytes + number of elements × 8 bytes – no rounding up is needed, as the result is always divisible by eight.

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

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

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

Total size = 16 bytes + 5 × 8 bytes
= 56 bytes

With object arrays, it is not the objects themselves that are stored in the array but the references to the objects – 4 bytes each with compressed oops. The following diagram shows the memory layout of the string array shown above:

Memory layout of a String array with four elements: 8-byte header, length field from byte 8, and four 4-byte references from byte 12 pointing to the String objects jujube, apple, boysenberry, and cherry, 32 bytes in total
A String array stores four references of 4 bytes each – the String objects themselves live elsewhere in the heap

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 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 an array of arrays. Therefore, we must add the memory space of the outer array and that of all the inner arrays.

The matrix with two rows and three columns from the first 2D example has the following memory layout:

Memory layout of a two-dimensional int array with two rows and three columns: the outer array with an 8-byte header, length field, two 4-byte references, and four bytes of padding, 24 bytes in total – each reference points to an inner int array with an 8-byte header, length field, and three elements, also 24 bytes
An int array with two rows and three columns consists of three objects: the outer array with two references and two inner int arrays

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

Total size = align(8 bytes + 4 bytes + number of rows × 4 bytes)
+ number of rows × align(8 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(8 bytes + 4 bytes + 2 × 4 bytes) + 2 × align(8 bytes + 4 bytes + 3 × 4 bytes)
= align(20 bytes) + 2 × align(24 bytes)
= 24 bytes + 2 × 24 bytes
= 72 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 JVM.

Where does this limit come from? Internally, HotSpot measures object sizes not in bytes but in words of 8 bytes – and some code paths pass that number of words around as an int. The worst case is a long array: each element takes up one word, plus two words for the header and the length field. For the sum to still fit into an int, such an array may have at most Integer.MAX_VALUE - 2 elements – and the same limit applies to all element types, including int and byte, whose arrays are far smaller when measured in words. You can look this up in arrayOop.hpp, method max_array_length().

The size in bytes plays no role for this limit – the int array of more than 8 GB takes up just over a billion words. 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 JVM:

TypesMaximum elementsMaximum size in the heap
boolean, byteInteger.MAX_VALUE - 22,147,483,664 bytes (~ 2 GB)
short, charInteger.MAX_VALUE - 24,294,967,304 bytes (~ 4 GB)
int, floatInteger.MAX_VALUE - 28,589,934,592 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 JVM 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 – length is a field, not a method. We can only set the length of an array when it is created; we cannot change it afterward.

Since Java 27, arrays have an 8-byte object header and a 4-byte length field, followed by the 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). Up to Java 26, the header was 12 bytes in size.

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

Did this article save you time? Then I’d be happy if you invested a minute of it in a review on my ProvenExpert profile. Your feedback shows me that the work on these articles pays off.

👉 Leave a review

Want Even More Knowledge?

My blog features many articles on Java, software architecture, and performance — from foundational concepts to advanced patterns.

If you want to go deeper, check out my trainings: hands-on, easy to understand, and directly applicable to your day-to-day project work. Instead of theory, I teach principles that help you write code that is better, more maintainable, and more performant in the long run.

Explore the Java Trainings

Become a Better Java Developer

My free newsletter keeps you ahead. Modern Java: new versions & features, performance, and JVM insights – once a month.

Search