While I was creating an array with size equals to Integer.MAX_VALUE
public static void main(String[] args) {
int[] array = new int[Integer.MAX_VALUE]; // This gives an Error
}
I got this Error :
Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds
VM limit at com.arrays.TimeArray2.main(TimeArray2.java:6)
Till now I Knew that an array in Java can, at the most, store up to 2,147,483,647 OR 2^31 values.
So I looked up on the Google for the reason behind this and found this Question on stackoverflow.com: Do Java arrays have a maximum size?.
The accepted answer over that discussion says :
In a recent HotSpot VM, the correct answer is Integer.MAX_VALUE - 5
Another popular answer states as :
Some VMs reserve some header words in an array. The maximum "safe" number would be
2,147,483,639 (Integer.MAX_VALUE - 8). Attempts to allocate larger arrays may
result in java.lang.OutOfMemoryError.
If you have the source code for the java classes, checkout
java.util.ArrayList.class (line 190):
But , the thing is none of the above is true (at least, not in my case). When i run the program with range as either of the above two values, I still kept getting the same Error.
Not only this, the error pops up even with the following set of values :
int[] array = new int[Integer.MAX_VALUE-10]; // Error
int[] array = new int[Integer.MAX_VALUE-100]; // Error
int[] array = new int[Integer.MAX_VALUE-1000]; // Error
int[] array = new int[2147483647]; // Error
int[] array = new int[214748364]; // Error
So, finally my question are :
1) What is the max. no. of elements which an array can store in Java ?
2) How to be sure that it is going to work on all the platforms (Or Multiple JVM implementations) satisfying the popular Java tagline Write Once Run Anywhere?