Arrays

6.4 Arrays

SYNTAX

DECLARATION
datatype variable[];

OR

datatype variable[size];

OR

datatype variable[]= {el_1,el_2 , ... ,el_n}
ALLOCATION
variable = new datatype[size];
REFERENCING ELEMENTS
variable[item]

DESCRIPTION

An array is an ordered collection of several objects of the same type. You can think of the objects as laying in a line, numbered from left to right. Arrays in Java have their elements numbered starting from 0.

The DECLARATION section above shows how to declare that a variable is an array. The first way declares only that variable will be an array the elements of which will be of type datatype. It declares neither the size nor the contents of the array. The second way initializes the array to be of length n with elements el_1,el_2, up to el_n as its contents.

If you do not initialize an array when you declare it, you will have to allocate before you use it. The syntax is shown in the ALLOCATION section above. Here we see the new keyword which is used to allocated memory for the array. Note that if the array is already allocated, and you reallocate this way, the variable will no longer contain its old contents.

You can reference elements using the syntax shown above. These references can be used anywhere in a Java statement that a variable name would be used. In particular, to assign to an array element you would use variable[item] = value;

Every array has an associated variable called length that contains the length of the array. If the array were called vector, then you would get the length of the array with vector.length.


EXAMPLE

The following code computes the dot product of two vectors. Here we use the analogy of an array of doubles as a vector.
     double dotprod{double vector_1[],double vector_2[]) {

       if( (vector_1.length==3) && (vector_2.length==3)) {
         for(double sum = 0, int i=0; i< vector_1.length; i++) {
           sum+=vector_1[i]*vector_2[i];
         }
         return sum;
       } else {
         return Double.NaN;
       }

     }
This method checks that the length of the two arrays are the same - it returns the IEEE float for Not A Number to signify an error (note that Java has a more elegant method of error handling that will not be discussed in this manual). If the arrays have the same length, it calculates and returns the dot product.

Some code that might use the dotprod method above might look like:


     double v1[];
     double v2[]={.3,.5.,.2};

     v1 = new double[3];
     for(int i=0;i<3;i++) {
       v1[i]=i*i;
     }

     double dp=dotprod(v1,v2);


Next 6.5 Classes

David Maxwell, who is still writing this, would like to hear your comments and suggestions.