Java has got a limit on the maximum array size your program can allocate. The exact limit is platform-specific but is generally between the somewhere 1 and 2.1 billion elements.
What is the reason?
This error is thrown by the native code within the JVM. This happens before allocating the memory for an array when the JVM performs platform-specific tasks, whether the allocated data structure is addressable in this platform.
- Your array grows too big and ends up having the size between the platform limit and the integer Max_LIMIT.
- You try to allocate the arrays larger than 2^31-1 elements to experiment with this limit.
Example:
When trying to recreate the java.lang.OutOfMemoryError: Requested array size exceeds VM limit error. Let's look at the following code;
for (int i = 3; i >= 0; i--) {
try {
int[] arr = new int[Integer.MAX_VALUE-i];
System.out.format("Successfully initialized an array with %,d elements.\n", Integer.MAX_VALUE-i);
} catch (Throwable t) {
t.printStackTrace();
}
}
The example iterates four times and initializes an array of long primitives on each turn. In this program, the size of an array is trying to initialize grows by one with every iteration and finally reaches Integer Max value.
Solution:
Initialize the array size with integer MAX_VALUE-2 to get rid of such errors;
int [] arr = new int[Integer.MAX_VALUE-2];