Instantiating Arrays

Contact Us or call 1-877-932-8228
Instantiating Arrays

Instantiating Arrays

Instantiate an array object using new, the data type, and an array size in square brackets

int[] nums;
nums = new int[10];

The second line constructs a new array object with 10 integer elements, all initialized to 0, and stores the reference into nums.

int[] moreNums;
int size = 7;
moreNums = new int[size];

You can declare and instantiate all at once:

String[] names = new String[3];

The elements of the array, String references, are initialized to null.

An array in memory

As objects, arrays also have a useful property: length:

  • In the above example, names.length would be 3.
  • The property is fixed (i.e., it is read-only).

You can reassign a new array to an existing variable:

int[] nums;
nums = new int[10];
nums = new int[20];

The original ten-element array is no longer referenced by nums, since it now points to the new, larger array.