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:
The output is:
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:
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.
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.