RU beehive logo ITEC dept promo banner
ITEC 120
2009spring
ibarland
nokie
jmdymacek

homeinfolectslabsexamshws
textbooktutor/PIsjava.lang docsjava.util docs

lect12a
arrays: intro

Suppose we want to write a program that deals with annual rainfall in the New River Valley. One way would be to have twelve different double variables:
rainInMonthAtIndex0, rainInMonthAtIndex1, rainInMonthAtIndex2, … rainInMonthAtIndex11.
(One might use month-numbers rather than month-names to keep all our variable-names similar1)

Clearly, declaring, initializing, and processing twelve different double variables is ugly. Hmmm, previously we took several related values and bundled them up into a single object (e.g. a potion-bottle's color, number-of-doses, and potency). Can we do the same with several related doubles? Yes!, and it's a type which is already built in to Java: “array of double”.

An array is a table of values, indexed starting from 0. For example, our twelve doubles could be handled as one object:

double[] rain;    // Declare a variable: its type is *array*-of-double.

rain = new double[12];   // Initialize ("allocate") the array.

// We now have twelve variables:
// rain[0], rain[1], rain[2], ..., rain[11]
// which we must initialize ouyrselves:

rain[0] = 2.3;
rain[1] = 4.1;
rain[2] = 3.7;
At this point, let's look at a picture of our object: in code pad, type “rain” and code pad will show the answer is “<object reference> (double[])”; double-click on the small red object-reference to see the actual object. The array is, conceptually, an object with twelve fields, named “0”, “1”, “2”, … “11”. However, to get/set these fields we use square-brackets: rain[index]. (Btw, what other field do we see inside the array object?)

Keep looking at the object as we continue initializing the array contents:

rain[3] = 4.2;
rain[4] = 0.0;
rain[5] = 2.7;
rain[6] = 0.0;
You can see visually, that we really are setting those entries in the array (table). By the way, can you look at the table and tell which entries we've initialized, and which we haven't? Yes, Java initialized the values for us (to 0.0, in the case of double[]). However, other people looking at our code may not be sure whether we wanted entries to be 0.0 or if we forgot to initialize the values (and, in case of a bug, they should spend time tracing this down). Also, other languages might not always initialize arrays. It's better to follow the simple rule:
programming tip: Always initialize all the entries of your array.
two things to remember: With regular variables, we had two steps: declare, then initialize. With arrays, we now have three steps: declare, initialize (“allocate”) the array itself, then initialize the contents of the array.

Syntax

The Java name for the type “array-of-double” is double[].
(Remember, one uses type-names when declaring variables, declaring fields, declaring parameters, and declaring a return-type.)
To construct an array2: new double[int]. To access the 7th item of the array rain: rain[7].
In general: array[index].

Looping over an array

In the code pad, we can continue on. Suppose we want to calculate the the average value. This sounds like a job for [what type of programming statment?] Yes! -- a loop.
What do we need to set up for every loop? Yes! An index-variable, and a so-far variable:

        int i = 0;
        double rainSoFar = 0.0;
        while (i <                  ) {
            rainSoFar = rainSoFar + rain[i];
            i = i + 1;
        }
After running this, we can look at rainSoFar / rain.length.

We can put this exact same thing inside a method:

    /** Calculate the average value in a given double[].
     * @param data The array to find the average of.
     * @return the average value of double[].
     */
    static                  avg(                  ) {
        int i = 0;
        double sumSoFar = 0.0;
        while (i <                  ) {
            sumSoFar = sumSoFar + data[i];
            i = i + 1;
        }
        return                 ;
    }
(See soln.)
The nice thing about putting this in its own method is that it now works for any array-of-doubles we ever make:
double[] scores = new double[2];
scores[0] = 92.5;
scores[1] = 98.0;

Looper.avg(scores)                  // Assuming the above static method is inside a class 'Looper'



double[] silly = new double[0];     // Not a very useful array at all.
                                    // Note: No contents need initializing, whew.

Looper.avg(silly);


1. But, why would you use 0..11 (indices) rather than 1..12 (ordinals)? Because it will be actually be more consistent in the long run. This also explains, by the way, why java.util.Calendar.JANUARY was written to be 0, not 1.      

2You might think the syntax would be new double[]( 12 ), since that follows Java's general rule of new TypeName( arg… ). However, array-constructors (just like getting and setting its (numeric) fields) have a slightly different syntax from the usual method syntax.)      

homeinfolectslabsexamshws
textbooktutor/PIsjava.lang docsjava.util docs


©2009, Ian Barland, Radford University
Last modified 2009.Apr.15 (Wed)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme