Arrays

An array is a data structure that is a collection of data of the same type. An array can have primitive types or objects.

Declaring an Array

An array can be declared the following way:
dataType [] arrayName;

or

dataType arrayName[];

boolean [] status;
int [] numPoints;
double [] xPos;

When you simply declare an array you have not created any space in memory for the contents of the array.

Creating an Array

You allocate space for an array by using the keyword new.
dataType [] arrayName = new dataType [ arraySize ];

char [] alphabet = new char [26];
The size of an array cannot be changed after it is created. array.length gives the size of an array. The array variable points to the first element of the array. The elements of the array so far are undefined.

Another way of creating the the array is to specify all the elements of the array:

short [] numList = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

Accessing Elements in an Array

An array is indexed from 0 to ( array.length - 1 ). To initialize an array element do
alphabet [2] = 'c';
arrayName[i] will return the array element at position i provided i is in the range 0 <= i < array.length.

Passing an Array to a Method

Primitive types are passed by value to methods. A reference to the array is passed to a method. Changes made to the array within the method will affect the contents of the original array.
public static int sumArray ( int[] anArray )
{
  int sum = 0;
  for ( int i = 0; i < anArray.length; i++ )
    sum += anArray[i];
  return sum;
}

Returning an Array from a Method

You can also return an array from a method. The syntax for doing so is shown below:
public static int[] copyArray ( int[] anArray )
{
  int[] dupArray = new int [anArray.length];
  for ( int i = 0; i < anArray.length; i++ )
    dupArray[i] = anArray[i];
  return dupArray;
}