JMU
Using Arrays
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Review
Opinions?
    income1 = 550.75;
    income2 =  25.60;
    income3 = 347.10;
    income4 = 120.45;
    income5 = 885.00;
    income6 =  10.99;
    income7 = 123.45;
    
Motivation
An Example from Algebra
An Array in Memory

An array is a contiguous block of memory that can be used to hold multiple homogeneous elements.

images/array.gif
Using Arrays in Java
When You Know All of the Elements "Up Front"

One can declare an array and assign all of the elements to it using an "array literal" (formally, an array initializer) as follows:

    char[]   course = {'C','S','1','3','9'};
    int[]    age    = {18, 21, 65};
    

One can then assign elements or access elements using the [] operator.

When You Don't Know All of the Elements "Up Front"

One can declare an array and assign default values to all of the elements to it as follows:

    char[]   course;
    int[]    age;

    course = new char[5];
    age    = new int[3];
    

One can then assign elements or access elements using the [] operator.

The Original Example Revisited
    int[] income;

    income = new int[7];

    income[0] = 550.75;
    income[1] =  25.60;
    income[2] = 347.10;
    income[3] = 120.45;
    income[4] = 885.00;
    income[5] =  10.99;
    income[6] = 123.45;
    
An Observation about Invalid Elements