How many elements arrays could contains in Java?

June 09, 2021 No comments Java array lenght max

1. Introduction

In this article, we will focus on maximum size of arrays in Java. Arrays are still widely used by developers even though Java offers other collections like Lists or Sets.

2. Array maximum size and JVM limitations

In Java, the array declaration requires a specific size of the array to be provided. The size of the array is given in int, so theoretically Java should be able to store the Integer.MAX_VALUE which is 2^31 – 1 = 2 147 483 647 items.

Let's check if this is true. First, we need a test program that will create an array with maximum size:

public class ArrayLenghtTest {

    public static void main(String[] args) {
        for (int i = 2; i >= 0; i--) {
            try {
                int size = Integer.MAX_VALUE - i;
                int[] arr = new int[size];
                System.out.printf("The maximum allow size is = %d%n", arr.length);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }
}

The output is:

java.lang.OutOfMemoryError: Java heap space
    at com.frontbackend.java.io.resources.ArrayLenghtTest.main(ArrayLenghtTest.java:9)
java.lang.OutOfMemoryError: Requested array size exceeds VM limit
    at com.frontbackend.java.io.resources.ArrayLenghtTest.main(ArrayLenghtTest.java:9)
java.lang.OutOfMemoryError: Requested array size exceeds VM limit

The first exception from the list is related to Java heap space, this happens because Java doesn't have enough memory to allocate such an array.

We need to increare Java heap size using -Xmx and -Xms parameters as VM arguments.

Let's check arguments: -Xms9G -Xmx9G:

The maximum allow size is = 2147483645
java.lang.OutOfMemoryError: Requested array size exceeds VM limit
    at com.frontbackend.java.io.resources.ArrayLenghtTest.main(ArrayLenghtTest.java:9)
java.lang.OutOfMemoryError: Requested array size exceeds VM limit
    at com.frontbackend.java.io.resources.ArrayLenghtTest.main(ArrayLenghtTest.java:9)

Now as you can see we get the maximum available size of the array which in our case is 2147483645. Note that this could be different on other JVM and machines.

OpenJDK developers suggest keeping the maximum size as Integer.MAX_VALUE - 8 - this should work on all JDK versions.

3. Conclusion

In this article, we focus on the maximum size of an array in Java. We checked that on our machine and JVM implementation we could create an array with 2147483645 items. This is a huge array that will be kept in the memory. We should consider if it is worth it and if there are no better options, such as using external memory databases for example.

{{ message }}

{{ 'Comments are closed.' | trans }}