Constructing an array

  • This step creates an actual array object on the heap memory with the specified size i.e.) number of elements this array will hold.
  • Size must be a positive integer value.
  • This is done using new keyword/operator.
  • This step is also known as instantiating an array, creating an array object, allocating memory space.

One dimensional array

double[] studentAvgs; //declaring an array reference
studentAvgs = new double[5]; //creating an array object or allocates memory for 5 elements

The preceding code creates a new array object on the heap holding five elements – with each element being a double with a default value 0.0

You can also declare and instantiate in a single statement.

double[] studentAvgs = new double[5]; //declare & allocate an array object

for example, the fifth element would be accessed at index 4.

Multidimensional array

A two dimensional array is simply an array object with each element in the array being a reference to another array.
Method 1:

double[][] studentAvgs; //declaring an array reference
studentAvgs = new double[3][]; //creating an array object

You can also declare and instantiate a two dimensional array in a single statement.

 double[][] studentAvgs = new double[3][];

Method 1 creates three rows and each row can hold any number of elements which can be defined later.

Method 2:

double[][] studentAvgs; //declaring an array reference
studentAvgs = new double[3][2]; //creating an array object

You can also declare and instantiate a two dimensional array in a single statement.

 double[][] studentAvgs = new double[3][2];

Method 2 creates three rows and each row referring to an array of two elements.

When creating a two dimensional array, you must provide row size.
double[][] studentAvgs = new double[][]; //ERROR

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.