Java Arrays

  1. A Java array is a reference to an array object. This implies that the array can be created without knowledge of the array size.

  2. A Java array reference can only be allocated on the heap (persistent). An array can therefore be allocated within a method and returned to the caller without becoming invalid.

  3. A Java array can be assigned to another array reference. The original array memory is then collected vy the garbage collector.

  4. An exception is thrown if the array is accessed with an index lower or higher than the array definition. This is a runtime check performed by the virtual machine. No adjacent memory is affected by such an overwrite error.

   int [] a1, a2;   // no size given
   a1 = new int[8]; // the array memory allocated on heap
   
   int [] a3 = {1,2,3,4};  // direct initialization
   a2 = a3;    // a2 and a3 now reference the same memory
   a2[10] = 5;  // ArrayOutOfBoundsException thrown