title: How do I know about the maximum range of elements which can be stored in an array?
body: <p>While I was creating an array with <em>size</em> equals to <strong>Integer</strong>.<em>MAX_VALUE</em></p>
  
  <pre><code>public static void main(String[] args) {
          int[] array = new int[Integer.MAX_VALUE]; // This gives an Error
  }
  </code></pre>
  
  <p>I got this Error :</p>
  
  <pre><code>Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds
  VM limit at com.arrays.TimeArray2.main(TimeArray2.java:6)
  </code></pre>
  
  <p>Till now I Knew that an array in Java can, at the most, store up to 2,147,483,647 OR 2^31 values.</p>
  
  <p>So I looked up on the Google for the reason behind this and found this Question on <em>stackoverflow.com</em>: <a href="https://stackoverflow.com/questions/3038392/do-java-arrays-have-a-maximum-size">Do Java arrays have a maximum size?</a>.</p>
  
  <p>The accepted answer over that discussion says :</p>
  
  <pre><code>In a recent HotSpot VM, the correct answer is Integer.MAX_VALUE - 5
  </code></pre>
  
  <p>Another popular answer states as :</p>
  
  <pre><code>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):
  </code></pre>
  
  <p>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.</p>
  
  <p>Not only this, the error pops up even with the following set of values :</p>
  
  <pre><code>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
  </code></pre>
  
  <p>So, finally my question are : </p>
  
  <p>1) What is the max. no. of elements which an array can store in Java ?</p>
  
  <p>2) How to be sure that it is going to work on all the platforms (Or Multiple JVM implementations) satisfying the popular Java tagline <strong>Write Once Run Anywhere</strong>?</p>