René Nyffenegger's collection of things on the web
René Nyffenegger on Oracle - Most wanted - Feedback -
 

Arrays [JAVA]

Declaration

There are two ways to declare an array:
dataType [] nameOfArray;
dataType    nameOfArray [];
No array size can be specifed. The following two lines do not compile:
int    a[5];
int[5] a;
Consider the following two lines:
int   a[], b;
int[] c,   d;
This makes a, c and d an array, while b is an int.

Constructing arrays

Arrays are constructed with the new operator. The array's size is stated within the brackets.
int [] a = new int[42];
int [] b;
b = new int[10];

Initializing an array

The following array's size is 10 and all elements in the array are initialized.
int[] squares = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100};

Multidimensional arrays

The following line creates an array with three elements. Each of these three elements is an array of 10 ints.
int[][] = new int [3][10];
The following example tries to demonstrate this.
public class array {

  public static void main(String[] args) {
    array array_ = new array();

    array_.fill_array();
  }

  void fill_array() {
    a = new int [3][10];

    for (int i=0; i<3; i++) {
      int[] a_10 = a[i];

      for (int j=0;j<10; j++) {
        a_10[j] = i+j;
      }
    }
  }

  int a[][];
}
The elements of a multidimensional array need not necessarlily have the same lengths. In the following example, the first element is an array of five ints, the second element is an array of three ints, the third element is not constructed, the fourth element is an array of zero ints, and the fifth element is an array of seven ints:
int[][] a = {
  { 1,  2,  3,  4,  5},
  {20, 30, 40        },
  null                ,
  {}                  ,
  new int[7]
};

length

length determines the size of an array. length does not need paraenthesis:
int [] a = new int [7];
System.out.println(a.length);