An Array
Previous    Next    Home    Source    Package

  1. Declaration and instantiation of an int array:
    int accumulator[] = new int[100];
  2. In the above, the expression to the left of = declares an object called accumulator to be capable of holding an array of elements of type int. Without the expression to the right of = the accumulator object has not a single int element. But, the expression new int[100] creates an array of 100 int elements and the = hands it to accumulator.
  3. Array elements are indexed from 0 (first element) to <array-name>.length-1 (the last element).
  4. The value of the ith element of array accumulator is obtained by the left side of = in the following
       int x = accumulator[i];
    The following access the first and last elements
       int x = accumulator[0];
       int y = accumulator[accumulator.length-1];
    So, the indices are 1 off what you expect them to be. Don't worry - you will get used to it.
  5. The value of an array element is set by using the assignment operator =, for example as follows
       accumulator[i] = 34;