Defining and Declaring Arrays

Contact Us or call 1-877-932-8228
Defining and Declaring Arrays

Defining and Declaring Arrays

An array stores a group of data items all of the same type.

An array is an object.

  • An array variable does not actually store the array - it is a reference variable that points to an array object.
  • Declaring the array variable does not create an array object instance; it merely creates the reference variable - the array object must be instantiated separately.
  • Once instantiated, the array object contains a block of memory locations for the individual elements.
  • If the individual elements are not explicitly initialized, they will be set to zero.
  • Arrays can be created with a size that is determined dynamically (but once created, the size is fixed).

Declare an array variable by specifying the type of data to be stored, followed by square brackets [].

dataType[] variableName;

You can read the [] as the word "array".

To declare a variable for an array of integers:

int[] nums;

...which you can read as "int array nums".

To declare a variable for an array of String objects:

String[] names;

...which you can read as "String array names" - the array holds String references.

You may also put the brackets after the variable name (as in C/C++), but that is less clearly related to how Java actually works.

int nums[]; // not recommended, but legal

But, that syntax does allow the following, which is legal, but seems like a bad practice.

int nums[], i, j; // declares one array and two single int values
Next