4.1.2.1 Arrays


An array is a data type for collecting data of the same type. Arrays contain a fixed number of elements (the size or length of the array), which is determined when the array is created. "Arrays" of variable sizes are provided by the Vector class. In this section you will learn the basics of arrays in Java.
  1. Declaring Arrays
  2. Instantiating Arrays
  3. Accessing Array Elements
  4. Copying Arrays
  5. Multidimensional Arrays

Declaring Arrays

An rray is an object. So before you can use it, you must first declare it. There are two equivalent ways of doing this: In general, we prefer the first way, as it clearly shows that it is the array of objects that has a name. Two concrete examples:
int[] arrayOfInts;
String arrayOfStrings[];
We defined an array of integers and of strings, respectively.

Instantiating Arrays

Next step in the creation of arrays is the instantiation. Like any object in Java this is done with the new operator. The following statement instantiates the arrayOfInts declared above to contain five integer elements.
arrayOfInts = new int[5];
We say that the size of the array (or the length of the array) equals five.

Both Java commands could have been combined into one statement:

int[] arrayOfInts = new int[5];
In general, you will often see statements of the form

elementType[] arrayName = new elementType[arraySize]

to create arrays. You can also create and initialize arrays at the same time: enclose array elements inside curly brackets, separated by commas. An example:
String[] arrayOfStrings = {"Joyful", "And", "Valuable", "Applets"};
creates an array of four strings. However, you cannot do this as an argument within a method. Then you separate the instantiation and the argument use.

Accessing Array Elements

Once an array has been instantiated you can assign its values and retrieve those values. All you have to keep in mind is that Java indexes the array elements from left to right starting at zero. The size of an array is stored in the read-only length instance variable.

Thus, the following array of integers has five elements accessible via p[0], p[1], p[2], p[3], and p[4], respectively.

int[] p = new int[5];
p[0] = 2;
p[1] = 3;
p[2] = 5;
p[3] = 7;
p[4] = 11;
p.length; // array size is 5
It is in most cases unwieldy to specify each element individually. It is often helpful to use for loops to initialize an array.
int[] squares = new int[50];
for (int i=0; i < squares.length; i++) {
  squares[i] = i*i;
}
The next example shows how you can build-up a table of the first fifty Fibonacci numbers. Recall the definition of Fibonacci numbers Fn by F0 = F1 = 1 and Fn  =  Fn-1  +  Fn-2  for n>1.
Java code
public class Fibonacci {
  public static void main(String[] args) {
     long fib[] = new long[50];
     fib[0] = 1;
     fib[1] = 1;
     for (int i=2; i<fib.length; i++) {
       fib[i] = fib[i-1] + fib[i-2];
     }
     for (int i=0; i<fib.length; i++) {
       System.out.println("fib[" + i + "] = " + fib[i]);
     }
  }
}
Output
fib[0] = 1
fib[1] = 1
fib[2] = 2
fib[3] = 3
fib[4] = 5
fib[5] = 8
fib[6] = 13
fib[7] = 21
fib[8] = 34
fib[9] = 55
...
...
fib[44] = 1134903170
fib[45] = 1836311903
fib[46] = 2971215073
fib[47] = 4807526976
fib[48] = 7778742049
fib[49] = 12586269025
When you access an element outside the range of an array, then an ArrayIndexOutOfBoundsException is thrown.

Copying Arrays

The System class provides a method called arraycopy for copying a range of elements from one array to another. It can be used to make a copy of a whole array, which can be manipulated without changing the original array. The assignment of one array to another via the = assignment operator would destroy elements in the original array while changing elements in the copy. The following example clarifies this.
Java code
public class copyTest {
  public static void main(String[] args) {
    //     initialization of  arrays
    int[] a = {1,2,3};
    int[] b = a;
    int[] c = new int[3];
    System.arraycopy(a,0,c,0,3);
    //     printing arrays
    for (int i=0; i<3; i++) {
      System.out.println("a["+i+"] = "+a[i]+
        ", b["+i+"] = "+b[i]+", c["+i+"] = "+c[i]);
    }
    System.out.println("");
    //    changing c
    for (int i=0; i<3; i++) {
      c[i]++;
    }
    //    printing arrays
    for (int i=0; i<3; i++) {
      System.out.println("a["+i+"] = "+a[i]+
         ", b["+i+"] = "+b[i]+", c["+i+"] = "+c[i]);
    }
    System.out.println("c changed; a and b unchanged");
    //    changing b
    for (int i=0; i<3; i++) {
      b[i]--;
    }
    //    printing arrays
    for (int i=0; i<3; i++) {
      System.out.println("a["+i+"] = "+a[i]+
         ", b["+i+"] = "+b[i]+", c["+i+"] = "+c[i]);
    }
    System.out.println("c unchanged; a and b changed");
  }
}
Output
a[0] = 1, b[0] = 1, c[0] = 1
a[1] = 2, b[1] = 2, c[1] = 2
a[2] = 3, b[2] = 3, c[2] = 3

a[0] = 1, b[0] = 1, c[0] = 2
a[1] = 2, b[1] = 2, c[1] = 3
a[2] = 3, b[2] = 3, c[2] = 4
c changed; a and b unchanged
a[0] = 0, b[0] = 0, c[0] = 2
a[1] = 1, b[1] = 1, c[1] = 3
a[2] = 2, b[2] = 2, c[2] = 4
c unchanged; a and b changed

Multidimensional Arrays

Java does not have true multidimensional arrays; they are faked by arrays of arrays. Below are some examples:
// a 3x3-matrix of integers (2-dim. array)
//
int[][] matrix = new int[3][3]; 
for (int row=0; row<3; row++) {
  for (int col=0; col<3; col++) {
    matrix[row][col] = row + col;
  }
}
//
// an array of size 3 consisting of 2-dim. arrays
//
int[][][] arrayOfMatrices = new int[3][][]; 
int[][] a = {{1,2}, {3,4}};
int[][] b = {{1,2,3}, {4,5,6}};
int[][] c = {{1,2}, {3,4}, {5,6}};
arrayOfMatrices[0] = a;
arrayOfMatrices[1] = b;
arrayOfMatrices[2] = c;
//
// a non-rectangular 2-dim. array
//
int[][] twodim = {{1}, {1,2}, {1,2,3}};