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;
}

Two-Dimensional Array

A two dimensional array can be looked upon as an array of arrays. It can be defined as:
final int ROWS = 3;
final int COLUMNS = 2;
int[][] a = new int [ROWS][COLUMNS];

This array has three rows and two columns

a[0][0] a[0][1]
a[1][0] a[1][1]
a[2][0] a[2][1]

To assign a value to any one element 

a[1][0] = 3;

Another way of declaring and assigning values to a two dimensional
array is

int[][] b = { {9, 8, 7}, {6, 5, 4}};

This is equivalent to

b[0][0] = 9  b[0][1] = 8  b[0][2] = 7
b[1][0] = 6  b[1][1] = 5  b[1][2] = 4

To sum over the elements of an array, sum over the columns first and
then the rows.

int sum = 0;

for ( int i = 0; i < ROWS; i++ )
  for ( int j = 0; j < COLUMNS; j++ )
    sum += a[i][j];