1. Overview
In this tutorial, we'll look at the maximum size of an array in Java.
2. Max Size
A Java program can only allocate an array up to a certain size. It generally depends on the JVM that we're using and the platform. Since the index of the array is int, the approximate index value can be 2^31 – 1. Based on this approximation, we can say that the array can theoretically hold 2,147,483,647 elements.
For our example, we're using the OpenJDK and Oracle implementations of Java 8 and Java 15 on Linux and Mac machines. The results were the same throughout our testing.
This can be verified using a simple example:
for (int i = 2; i >= 0; i--) {
try {
int[] arr = new int[Integer.MAX_VALUE - i];
System.out.println("Max-Size : " + arr.length);
} catch (Throwable t) {
t.printStackTrace();
}
}
During the execution of the above program, using Linux and Mac machines, similar behavior is observed. On execution with VM arguments -Xms2G -Xmx2G, we'll receive the following errors:
java.lang.OutOfMemoryError: Java heap space
at com.example.demo.ArraySizeCheck.main(ArraySizeCheck.java:8)
java.lang.OutOfMemoryError: Requested array size exceeds VM limit
at com.example.demo.ArraySizeCheck.main(ArraySizeCheck.java:8)
java.lang.OutOfMemoryError: Requested array size exceeds VM limit
Note that the first error is different from the last two. The last two errors mention the VM limitation, whereas the first one is about heap memory limitation.
Now let's try with the VM arguments -Xms9G -Xmx9G to receive the exact maximum size:
Max-Size: 2147483645
java.lang.OutOfMemoryError: Requested array size exceeds VM limit
at com.example.demo.ArraySizeCheck.main(ArraySizeCheck.java:8)
java.lang.OutOfMemoryError: Requested array size exceeds VM limit
at com.example.demo.ArraySizeCheck.main(ArraySizeCheck.java:8)
The results show the maximum size is 2,147,483,645.
The same behavior can be observed for byte, boolean, long, and other data types in the array, and the results are the same.
3. ArraySupport
ArraysSupport is a utility class in OpenJDK, which suggests having the maximum size as Integer.MAX_VALUE – 8 to make it work with all the JDK versions and implementations.
4. Conclusion
In this article, we looked at the maximum size of an array in Java.
As usual, all code samples used in this tutorial are available over on GitHub.
The post Maximum Size of Java Arrays first appeared on Baeldung.